我有一个列表:fruits = ['apple', 'orange', 'blueberry', Strawberry']
如何创建循环以使一个索引依赖于另一个索引:
for i in range(len(fruits)):
for j range(len(fruits[i+1:])):
print i,j
我想打印出这些对:
'apple', 'orange'
'orange', 'blueberry'
'blueberry', strawberry'
'orange', 'blueberry'
etc...
我想获得与c++语言对应的循环:
for(i=0;i<5;i++)
for (j=i+1; j<5; j++)
print i, j
最佳答案
如果您想要 C++ 代码打印出的内容,请使用 itertools.combinations
:
In [1]: import itertools
In [3]: fruits = ['apple', 'orange', 'blueberry', 'strawberry']
In [4]: for res in itertools.combinations(fruits, 2):
...: print res
...:
('apple', 'orange')
('apple', 'blueberry')
('apple', 'strawberry')
('orange', 'blueberry')
('orange', 'strawberry')
('blueberry', 'strawberry')
关于python - 循环索引依赖于前一个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42150804/