【问题标题】:Compare all elements of list between themselves比较列表中的所有元素
【发布时间】:2021-09-14 07:39:17
【问题描述】:

无论元组项目的顺序如何,如何计算列表中元组的出现次数?例如;

the_list = [
    (one, two, three),
    (two, three, four),
    (one, three, two),
    (one, two, three),
    (four, two, one),
]

在上面的列表中,我希望 (one, two, three)(one, three, two) 相等并被视为相同的东西。

【问题讨论】:

  • 你想使用permutations,而不是combinations
  • 您可能想要使用集合或冻结集合而不是元组。如果两个集合包含完全相同的值(无论它们的顺序如何),则它们相等。

标签: python python-3.x list tuples itertools


【解决方案1】:

您可以在开始计数之前使用计数器对它们进行排序

thelist = [(1,2,3), (2,3,4), (1,3,2), (1,2,3), (4,2,1)]
from collections import Counter
Counter(tuple(sorted(x)) for x in thelist)
Counter({(1, 2, 3): 3, (2, 3, 4): 1, (1, 2, 4): 1})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-29
    • 2023-03-22
    • 2015-09-30
    • 2023-04-03
    • 1970-01-01
    • 2020-02-21
    相关资源
    最近更新 更多