如何计算每个用户组中的项目数
我怎样才能输出这样的结果:
user I R H
=================
atl001 2 1 0
cms017 1 2 1
lhc003 0 1 2
从这样的列表:
atl001 I
atl001 I
cms017 H
atl001 R
lhc003 H
cms017 R
cms017 I
lhc003 H
lhc003 R
cms017 R
即我想计算每个 I
、H
和 R
的数量用户。请注意,在这种特殊情况下,我无法使用 itertools
中的 groupby
。预先感谢您的帮助。干杯!!
How can I output a result like this:
user I R H
=================
atl001 2 1 0
cms017 1 2 1
lhc003 0 1 2
from a list like this:
atl001 I
atl001 I
cms017 H
atl001 R
lhc003 H
cms017 R
cms017 I
lhc003 H
lhc003 R
cms017 R
i.e. I want to calculate the number of I
, H
and R
per user. Just a note that I can't use groupby
from itertools
in this particular case. Thanks in advance for your help. Cheers!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
结果
。
另外:
结果
。
PS:
用户的名字都是在L个字符中对齐的
在我的代码中,为了避免塞巴斯蒂安代码中的复杂性,I,R,H在相同数量的字符LL中对齐,这是最大的此列中出现的所有结果
result
.
Also:
result
.
PS:
The names of users are all justified in a number L of characters
In my code the columns, to avoid complexity as in the Sebastian's code, I, R , H are justified in the same number LL of characters, which is the max of all the results present in this columns
好吧,无论如何,使用
groupby
来解决这个问题是没有意义的。首先,您的数据未排序(groupby
不会为您对组进行排序),并且这些行非常简单。处理每一行时,只需记数即可。我假设您不知道会得到什么标志:
之后打印信息是迭代计数结构的问题。我假设用户名总是 6 个字符长:
上面的所有代码都未经测试,但应该大致可以工作。
Well, using
groupby
for this problem makes no sense anyway. For starters, your data isn't sorted (groupby
doesn't sort the groups for you), and the lines are very simple.Just keep count as you process each line. I am assuming you don't know what flags you'll get:
Printing the info after that is a question of iterating over your counts structure. I am assuming usernames are always 6 characters long:
All code above is untested, but should roughly work.
这是一个使用嵌套字典来计算作业状态并在打印前计算最大字段宽度的变体:
示例
这是一个使用平面字典并以元组
(user, status_name)
作为键的变体:用法和输出是一样的。
Here's a variant that uses nested dicts to count job statuses and computes max field widths before printing:
Example
Here's a variant that uses flat dictionary with a tuple
(user, status_name)
as a key:The usage and output are the same.
提示:
使用嵌套字典结构来计算出现次数:
user ->字符-> 的字符的出现
用户编写解析器代码并递增计数器并打印结果
取决于你......一个很好的练习。
As a hint:
Use a nested dictionary structure for counting the occurences:
user -> character -> occurences of the character for user
Writing the parser code and incrementing the counters and printing the result
is up to you ...a good exercise.