簡體   English   中英

循環遍歷python列表中每個配對元素的組合

[英]Looping through combination of each paired element in python list

我有一個列表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')這樣的組合不重復。 做這個的最好方式是什么?

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

嘗試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM