dm2111
dm2111

Reputation: 145

List comprehension combine 2 elements in nested list

Is it possible to use list comprehension to combine 2 elements in a nested list based on the occurrence of a character, eg: if you encounter '+' combine with the next element? I have some code that does this using nested loops, but trying to achieve using list comprehension.

Input: l = [['A-2', 'A-3', 'A-4', '+', '100', 'A-5'],['B-2', 'B-3', 'B-4', '+', '500', 'B-5']]

Output: l = [['A-2', 'A-3', 'A-4', '+100', 'A-5'],['B-2', 'B-3', 'B-4', '+500', 'B-5']]

Code:

for nested in l: 
   z = iter(nested)
   for i in z:
      if i == '+':
         i = i+next(z)

Upvotes: 1

Views: 277

Answers (1)

user2390182
user2390182

Reputation: 73470

The following will work:

[[x + next(i) if x == "+" else x for x in i] for i in map(iter, l)]

# [['A-2', 'A-3', 'A-4', '+100', 'A-5'], ['B-2', 'B-3', 'B-4', '+500', 'B-5']]

If the last element might be a "+", you could pass a default value to next

next(i, "")

to avoid an error.

Upvotes: 5

Related Questions