我有一个看起来像这样的元组列表。
[(1,2),(3,4),(2,1),(1,2),(2,3),(2,3)]
我想要这样的输出。
[(1,2,2),(3,4,1),(2,1,1),(2,3,2)]
元组中的第三个值是元组在列表中出现的次数。
迭代元组列表并在元组末尾添加值的有效方法是什么? 谢谢。
最佳答案
data = [(1, 2), (3, 4), (2, 1), (1, 2), (2, 3), (2, 3)]
from collections import Counter, OrderedDict
# Use Counter to find the number of times the tuple occured
d = Counter(data)
# Use OrderedDict to maintain the order of occurance
# Get tuples from OrderedDict and get count from d, create a new tuple
print [item + (d[item],) for item in OrderedDict.fromkeys(data)]
# [(1, 2, 2), (3, 4, 1), (2, 1, 1), (2, 3, 2)]
关于python - 迭代列表中的元组并为元组添加权重,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23319340/