1

I have a nested list of tuples, that I need to break out into a single list and drop the first ordinal of each. I can't seem to figure out how to accomplish this.

I have sample data such as:

[[('Item 1', <__main__.J object at 0x1018fc690>), ('Item 2', <__main__.J object at 0x1018fc6d0>)]]

and I am trying to reduce that to

[<__main__.J object at 0x1018fc690>, <__main__.J object at 0x1018fc6d0>]

Could someone please point me in the right direction. I've tried itertools and zip(*) to no avail.

import itertools
import operator

class J(object):
    pass

w = J()
w.Type = 'Item 1'
w.Page = 35
w.Fragment = 'AA'

q = J()
q.Type = 'Item 2'
q.Page = 78
q.Fragment = 'BA'

z = [[('Item 1', w),('Item 2', q)]]
y = [b for b in z]
print y

result = ([ a for a,b in z ], [ b for a,b in z ])
print result
print zip(*z)
Baywatch
  • 423
  • 5
  • 17
  • Is your input list always a list of lists of tuples, or is it arbitrarily nested? The answers so far are on the right track but it gets a bit more complicated if the nesting could be arbitrarily deep. – Peter DeGlopper Nov 01 '13 at 05:19
  • Yeah, the nesting is the issue that is hurting me. The solution by Christian works for my test case. – Baywatch Nov 01 '13 at 05:28

3 Answers3

7

This is what you are looking for?

result = [c[1] for b in z for c in b]
print result
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
3

Something like this?

>>> lis = [[(1, 'a'), (2, 'b')]]

zip:

>>> zip(*lis[0])[1]
('a', 'b')

List Comprehension:

>>> [y for _, y in lis[0]]
['a', 'b']
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0

As an alternative to @Christian's answer (and there's nothing wrong with that answer), you can also do this using itertools to flatten the list:

result = [c[1] for c in itertools.chain.from_iterable(z)]

I'd go with whichever construction you find easier to follow. Both assume only one level of nesting - dealing with arbitrarily deep nesting could be done with a recursive handler.

Peter DeGlopper
  • 36,326
  • 7
  • 90
  • 83
  • recursive handlers sound fun. I must check up on those. – Baywatch Nov 01 '13 at 05:39
  • If you get into that design, this answer looks like a decent start: http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python - except that you'd have to tweak it a bit because your lowest level elements are tuples, which are iterable. – Peter DeGlopper Nov 01 '13 at 05:42