Skip to main content
 首页 » 编程设计

python之迭代 Python 中的字符串列表

2025年05月04日41webabcd

让我们有一个字符串列表:fruit = ["apple", "orange", "banana"]。我想要一个打印出所有可能对的输出,即

apple - apple, apple - orange, apple - banana,  
orange - orange, orange - banana,  
banana - banana 

我的想法是枚举水果并执行以下操作:

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个字符串开始?

请您参考如下方法:

使用 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 

顺便说一句,你的固定代码在 enumerate 中看起来像这样:

fruit = ["apple", "orange", "banana"] 
 
for icnt, i in enumerate(fruit): 
     for jcnt in range(icnt,len(fruit)): 
        print ("{} - {}".format(i, fruit[jcnt]))