[英]Iteration over list of strings in 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个字符串开始?
使用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]))
不要重新发明轮子。 使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.