Zip嵌套列表与Python中的列表 [英] Zip nested list with list in Python

查看:124
本文介绍了Zip嵌套列表与Python中的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处是Python新手.我有四个列表,其中三个是嵌套列表,一个不是.我正在寻找一种用列表压缩嵌套列表的方法,以便zip函数将每个嵌套列表项目与主列表中的对应项目进行比较.

Python newbie here. I have four lists, three of which are nested lists and one that isn't. I'm searching for a way to zip the nested lists with the list such that the zip function compares each nested list item with the corresponding item in the main list.

main = [1,3]
a = [[1,2,3][4,5,6]]
b = [[0,1,2][3,4,5]]
c = [[2,3,4][5,6,7]]

>>>[[[True, False, False],[False,True,False],[False,False,False]],
[[False,False,False],[True,False,False],[False,False,False]]]

我尝试过这样的事情:

abc = zip(a,b,c)
test = (x==y for x, y in zip(main,*abc)

但是我收到错误消息太多值无法解包".有什么建议吗?

but I'm getting the error message "too many values to unpack". Any suggestions?

推荐答案

想法是使用已经压缩的abc列表zip() main列表,并嵌套列表理解:

The idea is to zip() the main list with the already zipped a, b and c lists and make a nested list comprehension:

>>> [[[item == x for item in l] for l in lists] 
     for x, lists in zip(main, zip(a, b, c))]
[[[True, False, False], [False, True, False], [False, False, False]], 
 [[False, False, False], [True, False, False], [False, False, False]]]

这篇关于Zip嵌套列表与Python中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆