我有一个元组列表,其中包含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元素的新值.
list_of_signs[] = [+,-,+,-,+.....11 values in each 'list_of_signs[]']
这是通过组合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 ]
目前我是:
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个元素的元组,依此类推.
标签:python,list-comprehension,list
来源: https://codeday.me/bug/20190609/1203982.html