nutship
nutship

Reputation: 4924

Joining tuple elements - list comprehension

We have this:

lst = [('543', 'Tom', '- Jerry'), ('544', 'X-man - ', 'Hulk')]`
lst = [h+a for n,h,a in lst]
lst =[name.split(' - ') for name in lst]

I want to first, join [1] and [2] element in each tuple together and split them on the - Splitting code will work but list comprehension for joining them does not.

We want the final output to be:

[('534', 'Tom, 'Jerry'), ('544', 'X-man', 'Hulk')]

With the code above we get only:

[('Tom, 'Jerry'), ('X-man', 'Hulk')]

@EDIT

I have another problem: sometimes my tuples contain only 2 items like this (2nd tuple): [('534', 'Tom, 'Jerry'), ('544', 'X-man - Hulk')] I want to get rid of the - so with the list comprehension from below I came up with this modified version: lst = [tuple(i.split(' - ') if len(tup) == 2 else tuple(i.strip(' - ') for i in tup) for tup in lst] which however raises an invalid syntax exception.

I'm sorry guys for asking again about similar issue but list comprehension is quite a new concept to me but if I get right the above I'll finish my program so I'm too impatient to study the whole documentation on the topic right now.

Upvotes: 0

Views: 1122

Answers (1)

root
root

Reputation: 80346

Maybe I am wrong, but do you really just want to strip off the whitespace and '-'?

In [15]: lst = [('543', 'Tom', '- Jerry'), ('544', 'X-man - ', 'Hulk')]

In [16]: [tuple(i.strip(' -') for i in tup) for tup in lst]
Out[16]: [('543', 'Tom', 'Jerry'), ('544', 'X-man', 'Hulk')]

Upvotes: 3

Related Questions