我有一个元组列表,其值和坐标为 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, '.')]
我有一个包含 5 个列表的列表:
list_of_signs = [['+', '+', '-', '+', '+', '+', '+', '-', '+', '+', '-'], ['+', '+', '-', '+', '-', '+', '+', '-', '+', '+', '-'], ['+', '+', '-', '+', '+', '+', '+', '-', '+', '+', '-'], ['+', '-', '-', '+', '+', '+', '+', '-', '+', '+', '-'], ['+', '+', '-', '+', '+', '+', '+', '-', '+', '+', '-']]
该列表中的每个列表都包含 i 个 +/- 值。这些 +/- 值对应于 dotted_array 中列表元素的新值。
list_of_signs[] = [+,-,+,-,+.....11 values in each 'list_of_signs[]']
这是组合来自 list_of_signs[] 的“值”和来自 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 ]
目前我是:
coord_list= [(x[0],x[1],list_of_signs[0][0]) for x in dotted_array]
得到:
[(0, 0, '+'), (2, 0, '+'), (3, 0, '+'), (0, 1, '+'), (2, 1, '+'), (0, 2, '+'), (2, 2, '+'), (3, 2, '+'), (0, 3, '+'), (2, 3, '+'), (3, 3, '+')]
这个输出不仅是错误的,而且也不一般。 我如何将此推广到所有 list_of_signs?
最佳答案
这是你想要的吗? -
>>> 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, '-')]]
zip
函数在每个索引处组合它作为参数接收的列表,因此返回的 zip 列表(或迭代器)的第 i 个索引将是第一个数组的第 i 个元素然后是第二个数组的第 i 个元素的元组,依此类推。
关于python - 在 Python 中,我如何使用列表理解来遍历列表列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31445190/