views:

74

answers:

3

Hi all,

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 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.

+1  A: 

This will give you the list you want:

[lx for li in fieldlist for lx in li[1] if li[1]]
sepp2k
Brilliant. I knew I had to have been close, but I didn't quite realize you could step through multiple lists like that. Thanks!
tjsimmons
A: 

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.

John Machin
It's a holdover from when I was printing out the lists, I wanted to skip the empty ones. I didn't realize it was redundant.
tjsimmons
A: 

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})
Piet Delport