开发者

List Comprehension in Nested Lists

I have a list like [["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.

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开发者_JAVA百科 thinking about this wrong, since I'm new to list comprehensions and Python.

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

Thanks.


This will give you the list you want:

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


A Pythonic solution would be something like:

>>> from collections import Counter
>>> Counter(v for (field, values) in fieldlist
...           for v in values)
Counter({'a': 2, 'b': 2, 'c': 1, 'f': 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] is an empty list or other container, the test is redundant. Otherwise you should edit your question to explain what else it could be.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜