-1

I have a list and want to separate each list element into more elements, if a comma appears. If a comma appears (Within l2 using this example) I want to duplicate the same element within l1 to match the numbers of commas found in l2. This may sound confusing, but below may explain this a bit better

l1 = ['1', '2', '3', '4', '5']
l2 = ['Sam', 'John', 'Steve, Harry, Lucy', 'Mike, Sam', 'Becky']

Intended output:

l1 = ['1', '2', '3', '3', '3', '4', '4', '5']
l2 = ['Sam', 'John', 'Steve', 'Harry', 'Lucy', 'Mike', 'Sam', 'Becky']

I tried x.split(',') within list, but this created multiple nested lists (shown below):

l2 = [['Sam'], ['John'], ['Steve', 'Harry', 'Lucy']] ..........
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Sam
  • 67
  • 4
  • You could follow up with this: https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists – Adam Jun 17 '20 at 11:05
  • 2
    Now you just need to iterate over the sublists in `l2`, while keeping track of the number of the sublist, and append that number to a new list repeatedly, according to the length of the sublist. – mkrieger1 Jun 17 '20 at 11:06

3 Answers3

1

This is your input:

names = ['Sam', 'John', 'Steve, Harry, Lucy', 'Mike, Sam', 'Becky']

This is my suggested solution:

l1, l2 = map(list, zip(*[(ix, i) for ix, split in 
            enumerate(map(lambda x: x.split(), names), 1) for i in split]))

The result:

[1, 2, 3, 3, 3, 4, 4, 5]
['Sam', 'John', 'Steve,', 'Harry,', 'Lucy', 'Mike,', 'Sam', 'Becky']

You don't even need l1 as input if you're only using increasing numbers.

Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143
1

You have some other answers that strike me as good but not very intuitive. Here's an alternative approach that doesn't require so much mental energy:

orig_nums = ['1', '2', '3', '4', '5']
orig_names = ['Sam', 'John', 'Steve, Harry, Lucy', 'Mike, Sam', 'Becky']

tups = [
    (n, nm)
    for n, names in zip(orig_nums, orig_names)
    for nm in names.split(', ')
]

for t in tups:
    print(t)

Output:

('1', 'Sam')
('2', 'John')
('3', 'Steve')
('3', 'Harry')
('3', 'Lucy')
('4', 'Mike')
('4', 'Sam')
('5', 'Becky')

You can easily separate tups into 2 separate lists if you truly need to, but any time I see someone operating on parallel lists, my first question is "Why not unify the data?" Sometimes there are good reasons, but you should make sure that you actually have one.

FMc
  • 41,963
  • 13
  • 79
  • 132
-1

You can use a list comprehension using zip to iterate over two lists in parallel:

from itertools import chain

l1 = ['1', '2', '3', '4', '5']
l2 = ['Sam', 'John', 'Steve, Harry, Lucy', 'Mike, Sam', 'Becky']

l1 = list(chain.from_iterable([[x] * len(y.split(',')) for x, y in zip(l1, l2)]))
l2 = list(chain.from_iterable([x.split(',') for x in l2]))
Austin
  • 25,759
  • 4
  • 25
  • 48