作者:mobiledu2502914875 | 来源:互联网 | 2022-11-30 17:30
我有一个如下所示的列表,我想找到一点点修改的简单排列,
例如
l=['a', 'b']
输出:
[('a', 'a'), ('a', 'b'), ('b', 'b')]
我跟着,
尝试-1
list(itertools.product(L, repeat=2))
回报,
[('a', 'a'), ('a', 'b'), ('b', 'a'), ('b', 'b')]
试试-2
print list(itertools.permutations(['a', 'b']))
回报,
[('a', 'b'), ('b', 'a')]
尝试-3
我可以这样做,
temp= [tuple(sorted((i,j))) for i in ['a', 'b'] for j in ['a', 'b']]
print list(set(temp))
但这似乎是解决这个问题的低效方法.
1> Daniel Mesej..:
使用combination_with_replacement:
from itertools import combinations_with_replacement
l=['a', 'b']
for c in combinations_with_replacement(l, 2):
print(c)
产量
('a', 'a')
('a', 'b')
('b', 'b')