简体   繁体   English

如何返回具有每个唯一字符串的元组列表以及给定的字符串列表的计数?

[英]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.

相关问题 如何计算列表中的唯一元组? - How to count unique tuples in the list? 如何在给定列表和元组元组的情况下创建将字符串映射到集合的字典? - How do I create a dictionary mapping strings to sets given a list and a tuple of tuples? 给定一个元组列表,通过串联返回一个字符串 - Given a list of tuples, return a string by concatenation 给定一个元组列表,如果第一个元素相同,我如何在每个相似的元组中添加第二个元素 - Given a list of tuples, if the first element is the same, how do i add the second element inside each similar tuple 如何在满足给定条件的字符串列表列表中返回计算字符串总数的整数列表? - How to return a list of integers that count total number of strings in a list of list of list of strings that satisfy a given condition? 如何枚举字符串列表,将每个字符串转换为它自己的列表? - How Do You Enumerate Over a List of Strings, Converting Each String to Its Own List? 如何通过 Python 中的列表中的每个值使列表中的随机值至少在给定数量上是唯一的? - How do I get random values in a list to be unique by at least a given amount by each value in the list in Python? 如何制作随机唯一元组的列表? - How do I make a list of random unique tuples? 计算嵌套列表中的唯一元组 - Count unique tuples in nested list 如何合并元组列表中的唯一值? - How do I combine unique values from a list of tuples?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM