python中如何遍历列表并将列表值赋予_在Python中,如何使用列表推导来遍历列表列表?...

我有一个元组列表,其中包含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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值