Hi, there's a list with tuples.

lst =  [('Meat', 'Milk'), ('Cake - Cookie',), ('Apple', 'Orange')]

For each tuple of len == 1 I want to split it at - so it results with:

lst = [('Meat', 'Milk'), ('Cake',  'Cookie'), ('Apple', 'Orange')]

I tried

[tuple(x.split(' - ') for x in tup) for tup in lst if len(tup) == 1]

It splits it up but the other tuples (of len == 2) are missing. Any suggestions please?

Edited by ytq_

4 Years
Discussion Span
Last Post by Lucaci Andrew

I used an oldfashioned loop to make it more clear ...

mylist = [('Meat', 'Milk'), ('Cake - Cookie',), ('Apple', 'Orange')]

newlist = []
for item in mylist:
    if '-' in item[0]:
        item = tuple(item[0].split(' - '))


''' result ...
('Meat', 'Milk')
('Cake - Cookie',)
('Cake', 'Cookie')
('Apple', 'Orange')
[('Meat', 'Milk'), ('Cake', 'Cookie'), ('Apple', 'Orange')]

Edited by vegaseat


I have tried several way to do this, not very clear but it works with one solution combining set and list comprehensions.

thelist=[('Meat', 'Milk'), ('Cake - Cookie',), ('Apple', 'Orange')]
ok=map(lambda z: map(lambda v: v.split(" - ") if " - " in v else v ,z),thelist)
print ok
for x in ok:
    print tuple(x)#whyyy "".join(x) don't works well but type(x) return list :(

so ...

print "map lambda, problem-> uncecessary nested lists and/or tuples "
thelist=[('Meat', 'Milk'), ('Cake - Cookie','z - z'), ('Apple', 'Orange')]
print map(lambda z: map(lambda v: v.split(" - ") if " - " in v else v ,z),thelist)
print "----"
print "list comprehensions, problem-> doublons"
print [[ tuple(item.split(" - ")) if " - " in item else tup for item in tup] for tup in thelist]
print "----"
print "sets with list comprehension :)"
[[ newlist.append(tuple(item.split(" - "))) if " - " in item else newlist.append(tup) for item in tup] for tup in thelist]
print list(set(newlist))
print "----"

i hope this will provide a few help


If using one-line examples, here, this might help you:

lst, l = [('Meat', 'Milk'), ('Cake - Cookie'), ('Apple', 'Orange')], []
[l.append(tuple(i.split(' - '))) if '-' in i else l.append(i) for i in lst]
print l

Should produce this output:

[('Meat', 'Milk'), ('Cake', 'Cookie'), ('Apple', 'Orange')]

Edited by Lucaci Andrew


Notice that the second tuple is a tuple and has a trailing comma, so
lst = [('Meat', 'Milk'), ('Cake - Cookie',), ('Apple', 'Orange')]

Votes + Comments
Good catch.

My apologies, thought I copied the right list, than indeed, this applies, which was already posted:

lst, l = [('Meat', 'Milk'), ('Cake - Cookie',), ('Apple', 'Orange')], []
[[l.append(tuple(j.split(' - '))) if '-' in j else l.append(j) for j in i] for i in lst]
print l
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.