[英]How do I return a list of tuples with each unique string and its count given a list of strings?
Not sure where to start... item() gives a dictionary and I don't want that. 不知道从哪里开始... item()给出了字典,我不想要那样。
I would say I need to loop through the list.... 我会说我需要遍历清单...。
Please someone give me some hints so I can get started! 请有人给我一些提示,让我开始吧!
EDIT: 编辑:
count_of_names(names)
counts_of_names(['John', John', 'Catherine', 'John', 'Christopher', 'Catherine']'
output: 输出:
[('Catherine', 2), ('Christopher', 1), ('John', 3)]
You may use collections.Counter()
to achieve this. 您可以使用
collections.Counter()
实现此目的。 Example: 例:
>>> x = [1,2,3,4,1,1,2,3]
>>> my_list = Counter(x).items()
>>> my_list
[(1, 3), (2, 2), (3, 2), (4, 1)]
# In order to sort the list base based on value of tuple at index `1` and then index `0`
>>> sorted(my_list, key=lambda x: (x[1], x[0]))
[(4, 1), (2, 2), (3, 2), (1, 3)]
This is a hard way to do it: 这是一种很难的方法:
x = [1,3,2,5,6,6,3,2]
x_tuple = []
y = set(x)
for i in y:
x_tuple.append((i,x.count(i)))
print(x_tuple)
Use set
and list comprehension: 使用
set
和列表理解:
def counts_of_names(names):
return [(name, names.count(name)) for name in set(names)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.