在Python中,如何使用列表推导来遍历列表列表?

Ket*_*omp 4 python list-comprehension list

我有一个元组列表,其中包含11个点的值和坐标

dotted_array = [(0, 0, '.'), (2, 0, '.'), (3, 0, '.'), (0, 1, '.'), (2, 1, '.'), (0, 2, '.'), (2, 2, '.'), (3, 2, '.'), (0, 3, '.'), (2, 3, '.'), (3, 3, '.')]
Run Code Online (Sandbox Code Playgroud)

我列出了5个清单:

list_of_signs = [['+', '+', '-', '+', '+', '+', '+', '-', '+', '+', '-'], ['+', '+', '-', '+', '-', '+', '+', '-', '+', '+', '-'], ['+', '+', '-', '+', '+', '+', '+', '-', '+', '+', '-'], ['+', '-', '-', '+', '+', '+', '+', '-', '+', '+', '-'], ['+', '+', '-', '+', '+', '+', '+', '-', '+', '+', '-']]
Run Code Online (Sandbox Code Playgroud)

该列表中的每个列表由i值+/-组成.这些+/-值对应于dotted_array中list元素的新值.

list_of_signs[] = [+,-,+,-,+.....11 values in each 'list_of_signs[]']
Run Code Online (Sandbox Code Playgroud)

这是通过组合list_of_signs []的'value'和来自dotted_array []的坐标的预期输出

coord_list = [[(0, 0, '+'), (2, 0, '+'), (3, 0, '-'), (0, 1, '+'), (2, 1, '+'), (0, 2, '+'), (2, 2, '+'), (3, 2, '-'), (0, 3, '+'), (2, 3, '+'), (3, 3, '-')], 4 More such lists ]
Run Code Online (Sandbox Code Playgroud)

目前我是:

coord_list= [(x[0],x[1],list_of_signs[0][0]) for x in dotted_array]
Run Code Online (Sandbox Code Playgroud)

要得到:

[(0, 0, '+'), (2, 0, '+'), (3, 0, '+'), (0, 1, '+'), (2, 1, '+'), (0, 2, '+'), (2, 2, '+'), (3, 2, '+'), (0, 3, '+'), (2, 3, '+'), (3, 3, '+')]
Run Code Online (Sandbox Code Playgroud)

这个输出不仅错误,而且不一般.如何对所有list_of_signs进行概括?

Ana*_*mar 5

这是你想要的吗? -

>>> dotted_array = [(1,2,'.'), (4,5,'.'),(1,2,'.'), (4,5,'.'),(1,2,'.'), (4,5,'.')]
>>> list_of_signs = [['+','-','-','+','+','-'],['-','-','+','+','+','-']]


>>> coord_list = [[(x[0][0],x[0][1],x[1]) for x in zip(dotted_array,s)] for s in list_of_signs]


>>> coord_list
[[(1, 2, '+'), (4, 5, '-'), (1, 2, '-'), (4, 5, '+'), (1, 2, '+'), (4, 5, '-')], [(1, 2, '-'), (4, 5, '-'), (1, 2, '+'), (4, 5, '+'), (1, 2, '+'), (4, 5, '-')]]
Run Code Online (Sandbox Code Playgroud)

zip 函数将它接收的列表作为参数组合在每个索引上,因此zip的返回列表(或迭代器)的索引将是第一个数组的第i个元素的元组,然后是第二个数组的第i个元素的元组,依此类推.

  • 使用模式匹配而不是索引可能看起来更清晰一点,即zip(dotted_array,l)中的`(coord_list = [[(a,b,op)for((a,b,_),op)for list_of_signs ]` (6认同)