我试图找到一种方法来迭代多个列表和一个计数器,但似乎无法做到。
alphabets = ['a', 'b', 'c']
numb = [1,2,3]
counter = 0
while (len(alphabets) != 0):
letter = alphabets[0]
alphabets.remove(letter)
for val in numb:
try:
print counter, letter, val
except Exception as e:
print "Failed with: ", counter, letter, val
counter = counter + 10
这是该程序的输出:
0 a 1
0 a 2
0 a 3
10 b 1
10 b 2
10 b 3
20 c 1
20 c 2
20 c 3
0 a 1
0 a 2
0 a 3
10 a 1
10 a 2
10 a 3
20 a 1
20 a 2
20 a 3
对于b和c也是等等。
所以基本上迭代27次而不是9次,同时用每个计数器触摸每个项目一次。如果不跳过任何计数器,我似乎无法做到正确。有任何想法吗?
这只是最多20个计数的一个例子。我想要做的是用字母表或麻木(或两者)来控制循环,这样对于包含n个项目的列表字母表,它将触及所有n个项目和计数器的麻木中的所有三个值,以及继续进行n次,直到字母表中没有足够的项目。
答案 0 :(得分:1)
假设counter
的最大长度为alphabet
:
alphabets = ['a', 'b', 'c']
numb = [1,2,3]
max_counter = len(alphabets) * 10
while (len(alphabets) != 0):
counter = 0
letter = alphabets[0]
alphabets.remove(letter)
while counter < max_counter:
for val in numb:
print counter, letter, val
counter += 10
但是,我会亲自编写这样的结构:
alphabets = ['a', 'b', 'c']
numb = [1,2,3]
max_counter = len(alphabets) * 10
for letter in alphabets:
# range max has to be max + inc to work.
for counter in range(0, max_counter, 10):
for number in numb:
print counter, letter,number
答案 1 :(得分:1)
只需使用三个for循环。
alphabets = ['a', 'b', 'c']
numb = [1, 2, 3]
for letter in alphabets:
for counter in range(0, 21, 10):
for val in numb:
print counter, letter, val