【问题标题】:Looping through combination of each paired element in python list循环遍历python列表中每个配对元素的组合
【发布时间】:2020-10-04 02:26:20
【问题描述】:

我有一个列表l = ['a', 'b', 'c'],我想循环遍历l 的每个配对元素的组合(顺序无关紧要)。正在做

import itertools
l= ['a', 'b', 'c']
for pair in itertools.product(l, l):
    print(pair)

产量:

('a', 'a')
('a', 'b')
('a', 'c')
('b', 'a')
('b', 'b')
('b', 'c')
('c', 'a')
('c', 'b')
('c', 'c')

但我想要类似的东西:

('a', 'a')
('a', 'b')
('a', 'c')
('b', 'b')
('b', 'c')
('c', 'c')

('a', 'b')('b', 'a') 这样的组合不会重复。 最好的方法是什么?

【问题讨论】:

  • 即您只想要该对的第一个元素大于或等于第二个元素的组合?或者您只想要独特的组合,您认为('a', 'b') 等于('b', 'a')
  • 是的,我想要 ('a', 'b') 等于 ('b', 'a') 的唯一组合

标签: python arrays list combinations


【解决方案1】:
import itertools
l = ['a', 'b', 'c']
for pair in itertools.combinations_with_replacement(l, 2):
    print(pair)

【讨论】:

    【解决方案2】:

    试试这个:

    arr=['a', 'b', 'c']
    for i in range(len(arr)):
      for x in arr[i:]:
        print((arr[i],x))
    

    【讨论】:

      猜你喜欢
      • 2014-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-04
      • 1970-01-01
      • 2013-11-25
      • 2018-07-11
      • 1970-01-01
      相关资源
      最近更新 更多