循环索引取决于前一个索引

Mon*_*ica 2 python loops

我有一个清单: fruits = ['apple', 'orange', 'blueberry', strawberry']

如何创建循环,使一个索引依赖于另一个索引:

for i in range(len(fruits)):
   for j range(len(fruits[i+1:])):
       print i,j
Run Code Online (Sandbox Code Playgroud)

我想打印成对:

'apple', 'orange'
'orange', 'blueberry'
'blueberry', strawberry'
'orange', 'blueberry'
etc...
Run Code Online (Sandbox Code Playgroud)

我想获得对应于c ++语言的循环:

 for(i=0;i<5;i++) 
     for (j=i+1; j<5; j++)
         print i, j
Run Code Online (Sandbox Code Playgroud)

ciz*_*ixs 5

如果您想要打印出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')
Run Code Online (Sandbox Code Playgroud)