我有一个列表: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...
我想打印出对:
for(i=0;i<5;i++)
for (j=i+1; j<5; j++)
print i, j
我想获得与c ++语言相对应的循环:
<ul>
<li class="menu" data-banner-text="A SELECTED"><a>A</a></li>
<li class="menu" data-banner-text="B SELECTED"><a>B</a></li>
<li class="menu" data-banner-text="C SELECTED"><a>C</a></li>
<li class="menu" data-banner-text="D SELECTED"><a>D</a></li>
</ul>
<div class="banner-header">
TEST
</div>
答案 0 :(得分: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')
答案 1 :(得分:1)
根据您的输出,我将使用此
fruits = ['apple', 'orange', 'blueberry', 'strawberry']
l = len(fruits)
for i in range(l):
for j in range(i, l - 1):
print fruits[j], fruits[j + 1]
输出:
apple orange
orange blueberry
blueberry strawberry
orange blueberry
blueberry strawberry
blueberry strawberry
答案 2 :(得分:0)
for i in range(len(fruits)-1):
print fruits[i], fruits[i+1]
答案 3 :(得分:0)
如果我理解正确,请尝试:
>>> fruits = ['apple', 'orange', 'blueberry', 'strawberry']
>>> from itertools import combinations
>>> list(combinations(fruits,2))
[('apple', 'orange'), ('apple', 'blueberry'), ('apple', 'strawberry'), ('orange', 'blueberry'), ('orange', 'strawberry'), ('blueberry', 'strawberry')]
或者,只是Python化您的C循环:
>>> for i in range(0, len(fruits)):
... for j in range(i+1, len(fruits)):
... print fruits[i], fruits[j]
...
apple orange
apple blueberry
apple strawberry
orange blueberry
orange strawberry
blueberry strawberry