我有一个 python 元组列表,如下所示:
listoftups = [('A', 'B'), ('C','D'), ('E','F'), ('G','H'), ('A','B'), ('C','D')]
我想计算此元组列表中的重复项数,并希望输出如下:
A -> B 2
C -> D 2
E -> F 1
G -> H 1
我怎样才能在python中做到这一点?我正在考虑使用计数器,但不确定。谢谢你。
您可以使用Counter
listoftups = [('A', 'B'), ('C','D'), ('E','F'), ('G','H'), ('A','B'), ('C','D')]
from collections import Counter
for k, v in Counter(listoftups).most_common():
print "{} -> {} {}".format(k[0], k[1], v)
输出
A -> B 2
C -> D 2
G -> H 1
E -> F 1
首先,使用集合获取包含非重复项的列表。然后遍历它们,并使用 count 以所需的格式打印它们:
listoftups = [('A', 'B'), ('C','D'), ('E','F'), ('G','H'), ('A','B'), ('C','D')]
listoftups = list(set(listoftups))
for el in listoftups:
print "{} -> {} {}".format(el[0], el[1], listoftups.count(el))
如果要保留订单,请创建如下的唯一值:
tmp = []
for el in listoftups:
if el not in tmp:
tmp.append(el)
然后执行我在第一个示例中所做的 for 循环。
import collections
result = collections.defaultdict(int)
def f(tup):
result[tup] += 1
map(lambda t: f(t), listoftups)
defaultdict(<type 'int'>, {('G', 'H'): 1, ('A', 'B'): 2, ('C', 'D'): 2, ('E', 'F'): 1})
您可以使用列表的计数方法:
listoftups = [('A', 'B'), ('C','D'), ('E','F'), ('G','H'), ('A','B'), ('C','D')]
tup = listoftups.count(('A', 'B')) # returns 2
并将它们全部计入字典:
result = dict()
for tup in set(listoftups):
result[tup] = listoftups.count(tup)
或更简洁地用字典理解:
result = {tup:listoftups.count(tup) for tup in set(listoftups)}
在你有一本字典之后:
result = { ('A', 'B'): 2, ('C', 'D'): 2, ('E','F'): 1, ('G', 'H'): 1}
你可以像fourtheye那样打印它,或者:
for k, v in result.items():
print k[0] + "->" + k[1] + " ", v
from collections import Counter
tuples = [('A', 'B'), ('C', 'D'), ('E', 'F'), ('G', 'H'), ('A', 'B'), ('C', 'D')]
counted = Counter(tuples).most_common()
s_t = sorted(counted, key=lambda x: x[0][0])
for key, value in s_t:
print key, value
上面的代码也会根据元组中第一个字符串的值进行排序。
控制台会话:
>>> from collections import Counter
>>> tuples = [('A', 'B'), ('C', 'D'), ('E', 'F'), ('G', 'H'), ('A', 'B'), ('C', 'D'), ('C', 'D'), ('C', 'D')]
>>> counted = Counter(tuples).most_common()
>>> counted
Out[8]: [(('C', 'D'), 4), (('A', 'B'), 2), (('G', 'H'), 1), (('E', 'F'), 1)]
>>> sorted_tuples = sorted(counted, key=lambda x: x[0][0])
>>> sorted_tuples
Out[10]: [(('A', 'B'), 2), (('C', 'D'), 4), (('E', 'F'), 1), (('G', 'H'), 1)]