迭代Python中的字符串列表

时间:2017-01-11 15:06:58

标签: python

让我们有一个字符串列表: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个字符串开始?

2 个答案:

答案 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