python - 在 Python 中,我如何使用列表理解来遍历列表列表?

标签 python list list-comprehension

我有一个元组列表,其值和坐标为 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/

相关文章:

python - 如何按定义的顺序遍历 Python 字典?

Python 附加列标题并将列值从列表附加到 csv

python - 如何使用 lambda 在 for 循环内创建 if ?

Python - 在和不在列表语法错误中

list - 如何交换序言列表中的三乘三元素?

python - for循环前的数字是什么意思

python - 如何在 Pandas DataFrame 中一次获取多列的值计数?

python - 当某些列不存在时从 DataFrame 中删除列列表

python - 如何分析 Python 代码以识别有问题的区域?

html - 使用 li :before? 时如何正确调整元素符号大小