【问题标题】:Python: How to count the tuple ('a' , 'b') and tuple ('b', 'a') in a list as the same thing ? [duplicate]Python:如何将列表中的元组('a','b')和元组('b','a')计算为同一事物? [复制]
【发布时间】:2018-04-17 13:03:21
【问题描述】:

我想得到以下结果:

Input:  list = [('a' , 'b'), ('b', 'a'), ('c', 'd'), ('d','e'), ('e','d')] 
Output: Counter({('a','b'):2,('c','d'):1, ('d','e'):2})

我尝试将计数器实现为:

count = Counter(list)

它只能返回:

Counter({('a', 'b'):1,  ('b', 'a'):1, ('c', 'd'):1,  ('d', 'e'):1, ('e','d'):1})

【问题讨论】:

  • 先对元组排序?
  • 另外,不要列出list,因为它会覆盖内置名称。
  • Counter 是什么?
  • @CristiFati collections.Counter
  • 谢谢@pault:d。我的错。

标签: python list count tuples


【解决方案1】:

先简单地对元组进行排序:

In [21]: l = [tuple(sorted(i)) for i in l]

In [22]: l
Out[22]: [('a', 'b'), ('a', 'b'), ('c', 'd'), ('d', 'e'), ('d', 'e')]

In [23]: Counter(l)
Out[23]: Counter({('a', 'b'): 2, ('c', 'd'): 1, ('d', 'e'): 2})

【讨论】:

  • 非常感谢!!!。有用。我已经搜索了很多次以学习如何对元组中的元素进行排序,但一无所获。大多数答案是如何对所有元组进行排序。
【解决方案2】:

您可以将collections.defaultdictfrozenset 一起使用。

这是因为frozenset 是可散列的,因此可以用作字典中的键。

如果不保存订单是目标,那么这是每次排序的一个很好的替代方案。

from collections import defaultdict

lst = [('a' , 'b'), ('b', 'a'), ('c', 'd'), ('d','e'), ('e','d')]

d = defaultdict(int)

for i in map(frozenset, lst):
    d[i] += 1

# defaultdict(int,
#             {frozenset({'a', 'b'}): 2,
#              frozenset({'c', 'd'}): 1,
#              frozenset({'d', 'e'}): 2})

【讨论】:

  • 也可以Counter(map(frozenset, lst))
  • @chrisz,确实如此。我想做一些测试它是否会更有效。我被告知 Counter 有纯 Python 位,而 defaultdict 都是 C。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-29
  • 2011-12-23
  • 2021-02-18
  • 2021-10-06
  • 2020-07-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多