【问题标题】:Python3 List Comprehension for n listsn个列表的Python3列表理解
【发布时间】:2020-05-30 22:02:39
【问题描述】:

我有一种方法可以按照我的意愿遍历我的列表,如下所示:

a = ["1","2","3","4","5","6","7","8","9","10"]
b = ['A','B','C','D','E','F','G','H','I','J']
c = ["11","12","13","14","15","16","17","18","19","20"]

for x, y, z in [(x,y,z) for x in a for y in b for z in c]:
    print(x,y,z)

输出:

1 A 11
1 A 12
1 A 13
1 A 14
1 A 15
1 A 16
1 A 17
1 A 18
1 A 19
1 A 20
1 B 11
1 B 12
1 B 13
1 B 14
...etc

但是,如果我的列表存储在一个列表中并且有 n 个列表,我怎样才能获得相同的结果?例如

main_list=[["1","2","3","4","5","6","7","8","9","1"],['A','B','C','D','E','F','G','H','I','J'],["11","12","13","14","15","16","17","18","19","20"],['k','l','m','n','o','p','q','r','s','t']]

提前致谢。

【问题讨论】:

  • 看看zip function。本质上,如果main_list 包含所有列表,zip(*main_list) 应该会给你你想要的。
  • zip 不会这样做。 zip 只会给出“1 A 11, 2 B 12, 3 C 13, ...”

标签: python-3.x list list-comprehension


【解决方案1】:

itertools.product

a = ["1","2","3","4","5","6","7","8","9","10"]
b = ['A','B','C','D','E','F','G','H','I','J']
c = ["11","12","13","14","15","16","17","18","19","20"]

from itertools import product

all_lists = [a, b, c]
for c in product(*all_lists):
    print(c)

打印:

('1', 'A', '11')
('1', 'A', '12')
('1', 'A', '13')
('1', 'A', '14')
('1', 'A', '15')
('1', 'A', '16')
('1', 'A', '17')
('1', 'A', '18')
('1', 'A', '19')
('1', 'A', '20')
('1', 'B', '11')

... and so on.

【讨论】:

    【解决方案2】:

    例如,下面给出了所需的组合。

    import itertools
    
    list(itertools.product(*(a,b,c)))
    
    

    对于主列表 -

    
    main_list=[["1","2","3","4","5","6","7","8","9","1"],['A','B','C','D','E','F','G','H','I','J'],["11","12","13","14","15","16","17","18","19","20"],['k','l','m','n','o','p','q','r','s','t']]
    
    combintns = list(itertools.product(*main_list))
    
    # in case you're specific about output format/appearance
    for i in combintns:
      print(i[0],i[1],i[2],i[3])
    

    【讨论】:

      猜你喜欢
      • 2016-02-06
      • 1970-01-01
      • 2018-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-25
      • 2016-07-01
      相关资源
      最近更新 更多