hobbes
hobbes

Reputation: 467

How do I split items in a list (with delimiter) within a list?

UPDATE: Sorry guys, I meant to say a list, within a list.

How do I split items in a list, within another list, using a delimiter. For example:

x = [['temp1_a','temp2_b', None, 'temp3_c'],['list1_a','list2_b','list3_c']]

Ideally, I would like to split them into a dictionary, so:

y = ['temp1','temp2', None, 'temp3','list1','list2','list3']
z = ['a','b', None, 'c','a','b','c']

I'm sure it uses split, but when I try using it, I get 'list' object has no attribute 'split'.

Upvotes: 0

Views: 179

Answers (4)

jwilner
jwilner

Reputation: 6606

It's that time of the night, so I thought I'd write a recursive python 3 generator.

def flatten_list(a_list):
    for element in a_list:
        if isinstance(element, list):
            yield from flatten_list(element)
        else:
            yield element

# {"temp1": "a", "temp2": "b"...}
values = dict(string.split('_') 
              for string in flatten_list(x)
              if string is not None)

Upvotes: 0

AChampion
AChampion

Reputation: 30258

There are many ways to do this...

>>> from itertools import chain
>>> y, z = zip(*([None]*2 if not i else i.split('_') for i in chain(*x)))
>>> y
('temp1', 'temp2', None, 'temp3', 'list1', 'list2', 'list3')
>>> z
('a', 'b', None, 'c', 'a', 'b', 'c')

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174706

Use list_comprehension.

>>> x = ['temp1_a','temp2_b', None, 'temp3_c']
>>> y, z  = [i if i is None else i.split('_')[0] for i in x ], [i if i is None else i.split('_')[1] for i in x ]
>>> y
['temp1', 'temp2', None, 'temp3']
>>> z
['a', 'b', None, 'c']

Update:

>>> x = [['temp1_a','temp2_b', None, 'temp3_c'],['list1_a','list2_b','list3_c']]
>>> y, z = [i if i is None else i.split('_')[0] for i in itertools.chain(*x)], [i if i is None else i.split('_')[1] for i in itertools.chain(*x) ]
>>> y
['temp1', 'temp2', None, 'temp3', 'list1', 'list2', 'list3']
>>> z
['a', 'b', None, 'c', 'a', 'b', 'c']

Upvotes: 2

Shashank
Shashank

Reputation: 13869

Here is how I would do it using list comprehensions:

xp = [(None,)*2 if i is None else i.split('_') for i in x]
y, z = map(list, zip(*xp))

The right-hand side expression on the second line is just an elegant way of writing:

[i[0] for i in xp], [i[1] for i in xp]

Upvotes: 2

Related Questions