1

我想听听你关于解决多个列表上的循环问题的想法。我有多个不同长度的列表,例如: ['dog','cat'], [5,45,8,9], ['yellow','blue','black'].

我希望能够像这样访问这些列表的元素:

1. ['dog', 5, 'yellow']
2. ['dog', 5, 'blue']
3. ['dog', 5, 'black']
4. ['dog', 45, 'yellow']
5. ['dog', 45, 'blue']
6. ['dog', 45, 'black']
7. ['dog', 8, 'yellow']
8. ['dog', 8, 'blue']
9. ['dog', 8, 'black']
10. ['dog', 9, 'yellow']
11. ['dog', 9, 'blue']
12. ['dog', 9, 'black']
13. ['cat', 5, 'yellow']
14. ['cat', 5, 'blue']
15. ['cat', 5, 'black']
16. ['cat', 45, 'yellow']
17. ['cat', 45, 'blue']
18. ['cat', 45, 'black']
19. ['cat', 8, 'yellow']
20. ['cat', 8, 'blue']
21. ['cat', 8, 'black']
22. ['cat', 9, 'yellow']
23. ['cat', 9, 'blue']
24. ['cat', 9, 'black']

谢谢。我必须重新发布它,因为格式使它笨拙并且有点难以阅读

4

2 回答 2

7

您正在寻找itertools.product

>>> from itertools import product
>>> animal = ['dog','cat']
>>> number = [5,45,8,9]
>>> color = ['yellow','blue','black']
for i,p in enumerate(product(animal, number, color),1):
    print "{}. {}".format(i,str(list(p)))
...     
1. ['dog', 5, 'yellow']
2. ['dog', 5, 'blue']
3. ['dog', 5, 'black']
4. ['dog', 45, 'yellow']
5. ['dog', 45, 'blue']
6. ['dog', 45, 'black']
7. ['dog', 8, 'yellow']
8. ['dog', 8, 'blue']
9. ['dog', 8, 'black']
10. ['dog', 9, 'yellow']
11. ['dog', 9, 'blue']
12. ['dog', 9, 'black']
13. ['cat', 5, 'yellow']
14. ['cat', 5, 'blue']
15. ['cat', 5, 'black']
16. ['cat', 45, 'yellow']
17. ['cat', 45, 'blue']
18. ['cat', 45, 'black']
19. ['cat', 8, 'yellow']
20. ['cat', 8, 'blue']
21. ['cat', 8, 'black']
22. ['cat', 9, 'yellow']
23. ['cat', 9, 'blue']
24. ['cat', 9, 'black']
于 2013-07-08T19:30:56.597 回答
2

一种更“行人”的方式来遍历不同的列表并制作一个组合列表:

animal = ['dog','cat']
number = [5,45,8,9]
color = ['yellow','blue','black']
num = 0
combined = []

for a in animal:
  for n in number:
    for c in color:
      print a, n, c
      combined.append([a, n, c])

print combined

将此确切代码保存在文件animal.py中,并从命令行运行它,python animal.py结果如下:

dog 5 yellow
dog 5 blue
dog 5 black
dog 45 yellow
dog 45 blue
dog 45 black
dog 8 yellow
dog 8 blue
dog 8 black
dog 9 yellow
dog 9 blue
dog 9 black
cat 5 yellow
cat 5 blue
cat 5 black
cat 45 yellow
cat 45 blue
cat 45 black
cat 8 yellow
cat 8 blue
cat 8 black
cat 9 yellow
cat 9 blue
cat 9 black
[['dog', 5, 'yellow'], ['dog', 5, 'blue'], ['dog', 5, 'black'], ['dog', 45, 'yellow'], ['dog', 45, 'blue'], ['dog', 45, 'black'], ['dog', 8, 'yellow'], ['dog', 8, 'blue'], ['dog', 8, 'black'], ['dog', 9, 'yellow'], ['dog', 9, 'blue'], ['dog', 9, 'black'], ['cat', 5, 'yellow'], ['cat', 5, 'blue'], ['cat', 5, 'black'], ['cat', 45, 'yellow'], ['cat', 45, 'blue'], ['cat', 45, 'black'], ['cat', 8, 'yellow'], ['cat', 8, 'blue'], ['cat', 8, 'black'], ['cat', 9, 'yellow'], ['cat', 9, 'blue'], ['cat', 9, 'black']]

如果你想要一个特定的元素,你现在可以做(例如)

print "element 3 is ", combined[3]

这将返回

element 3 is  ['dog', 45, 'yellow']
于 2013-07-08T19:34:07.007 回答