简体   繁体   English

嵌套列表中的列表理解

[英]List Comprehension in Nested Lists

I have a list like [["foo", ["a", "b", "c"]], ["bar", ["a", "b", "f"]]] 我有一个列表,例如[["foo", ["a", "b", "c"]], ["bar", ["a", "b", "f"]]]

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. 并且我想将其拆分,以便可以获取As,B等的总数。但是我是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 for lx in [li[1] for li in fieldlist if li[1]]]尝试获取包含子子列表中所有项目的列表,但是该列表返回第一个子列表( [["a", "b", "c"], ["a", "b", "f"]]而不是包含这些子列表内容的列表。我敢肯定,只是想想这个错误,因为我是刚开始列出理解和Python的人。

Anyone have a good way to do this? 有人有这样做的好方法吗? (and yes, I know the names I chose (lx, li) are horrible) (是的,我知道我选择的名字(lx,li)太可怕了)

Thanks. 谢谢。

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

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

List comprehension: 清单理解:

>>> s = [["foo", ["a", "b", "c"]], ["bar", ["a", "b", "f"]]]
>>> [x for y, z in s for x in z]
['a', 'b', 'c', 'a', 'b', 'f']
>>>

What is the purpose of your if li[1] ? if li[1]什么? If li[1] is an empty list or other container, the test is redundant. 如果li[1]是一个空列表或其他容器,则该测试是多余的。 Otherwise you should edit your question to explain what else it could be. 否则,您应该编辑问题以解释其他问题。

A Pythonic solution would be something like: Pythonic解决方案将类似于:

>>> from collections import Counter
>>> Counter(v for (field, values) in fieldlist
...           for v in values)
Counter({'a': 2, 'b': 2, 'c': 1, 'f': 1})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM