【问题标题】:Concatenate elements of identical lists without duplicates python连接相同列表的元素而不重复python
【发布时间】:2017-01-11 13:26:03
【问题描述】:

如图所示,我有 2 个相同的列表:

list_1 = ['A','B','C','D','E','F']
list_2 = ['A','B','C','D','E','F']

我将其中的每个元素连接起来,

for i in list_1:
    for j in list_2:
        print(i+' and '+j)

您能帮我删除可能出现的重复组合吗?(例如:AA、..FF 以及 AB、AC、BC 等)

提前致谢!

【问题讨论】:

  • 这是一个 XY 问题的案例。您不需要两个相同的列表,只需一个列表和iterations.combinations
  • 您还想要CA、CB等吗?
  • 对@JoelCornett,实际代码仅包含一个列表,并且是组合的情况。这是我想出的一个简单的例子,我没有想到;)

标签: python list logic


【解决方案1】:

您只需执行比较并将其限制为 i 小于 j

for i in list_1:
    for j in list_2:
        if i < j:
            print(i+' and '+j)

由于打印'A and B'的顺序约束,这意味着A小于B,因此意味着约束'A' &gt; 'B'将失败,因此不会打印B and A

【讨论】:

  • @barakmanos: 顺序也在str 对象上定义:这里使用字典顺序。只要&lt; 是数学上的非自反顺序关系(非自反、传递和不对称),它就可以工作。
【解决方案2】:

使用itertools.combinations。在这种情况下,代码变得更加简单。您只需要一个列表,combinations 会自动为您生成唯一的组合。所以你没有过滤'AA'或'CB'只传递'BC'。

>>> from itertools import combinations

>>> l=['A','B','C','D','E','F']

list(combinations(l, 2))
[('A', 'B'), ('A', 'C'), ('A', 'D'), ('A', 'E'), ('A', 'F'), 
 ('B', 'C'), ('B', 'D'), ('B', 'E'), ('B', 'F'), 
 ('C', 'D'), ('C', 'E'), ('C', 'F'), 
 ('D', 'E'), ('D', 'F'), 
 ('E', 'F')]

>>> # or with joined strings
>>> [' and '.join(x) for x in combinations(l, 2)]
['A and B', 'A and C', 'A and D', 'A and E', 'A and F', 
 'B and C', 'B and D', 'B and E', 'B and F', 
 'C and D', 'C and E', 'C and F', 
 'D and E', 'D and F', 
 'E and F']

我已经格式化了输出,看看你有没有干净的结果。

【讨论】:

    猜你喜欢
    • 2013-05-07
    • 2020-12-24
    • 1970-01-01
    • 2018-09-20
    • 2022-01-25
    • 2021-12-10
    • 2022-06-10
    • 1970-01-01
    • 2020-01-25
    相关资源
    最近更新 更多