让我们有一个字符串列表:fruit = ["apple", "orange", "banana"]
。我希望有一个输出打印出所有可能的对,即
apple - apple, apple - orange, apple - banana,
orange - orange, orange - banana,
banana - banana
我的想法是enumerate
果实并做以下事情:
for icnt, i in fruit:
jcnt = icnt
j = i
print ("icnt: %d, i: %s", icnt, i)
for jcnt, j in fruit:
print ("i: %s, j: %s", i, j)
期望字符串不是从icnt-th
位置开始,而是从开始。如何使第二个循环从第i个字符串开始?
答案 0 :(得分:3)
使用itertools.combinations_with_replacement
执行此操作:
import itertools
for a,b in itertools.combinations_with_replacement(["apple", "orange", "banana"],2):
print("{} - {}".format(a,b))
输出:
apple - apple
apple - orange
apple - banana
orange - orange
orange - banana
banana - banana
或itertools.combinations
如果您不想重复:
apple - orange
apple - banana
orange - banana
BTW您的固定代码看起来像是enumerate
:
fruit = ["apple", "orange", "banana"]
for icnt, i in enumerate(fruit):
for jcnt in range(icnt,len(fruit)):
print ("{} - {}".format(i, fruit[jcnt]))
答案 1 :(得分:2)
不要重新发明轮子。使用itertools
:
from itertools import combinations_with_replacement
fruit = ["apple", "orange", "banana"]
print('\n'.join((' - '.join(perm) for perm in combinations_with_replacement(fruit, 2))))
# apple - apple
# apple - orange
# apple - banana
# orange - orange
# orange - banana
# banana - banana