嵌套列表中的列表理解 [英] List Comprehension in Nested Lists

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

问题描述

我有一个类似[["foo", ["a", "b", "c"]], ["bar", ["a", "b", "f"]]]

我想将其拆分出来,这样我就可以计算出As,B等的总数.但是我是Python的新手,并且花了一点时间.

and I'm wanting to split it out so I can get a count of the total number of As, Bs, etc. but I'm new to Python and having a bit of a time of it.

我正在使用[lx for lx in [li[1] for li in fieldlist if li[1]]]尝试获取包含子子列表中所有项目的列表,但是它返回包含第一个子列表的列表([["a", "b", "c"], ["a", "b", "f"]]而不是包含这些子列表内容的列表.我很确定我只是在考虑这个错误,因为我是新的列出理解和Python的人.

I'm using [lx for lx in [li[1] for li in fieldlist if li[1]]] to try and get a list with all of the items in the sub-sublists, but that returns a list with the first sublists ([["a", "b", "c"], ["a", "b", "f"]] instead of a list with the contents of those sublists. I'm pretty sure I'm just thinking about this wrong, since I'm new to list comprehensions and Python.

有人有做到这一点的好方法吗? (是的,我知道我选择的名字(lx,li)太可怕了)

Anyone have a good way to do this? (and yes, I know the names I chose (lx, li) are horrible)

谢谢.

推荐答案

这将为您提供所需的列表:

This will give you the list you want:

[lx for li in fieldlist for lx in li[1] if li[1]]

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

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