1

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)
dm2111
  • 135
  • 1
  • 6

1 Answers1

5

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.

user2390182
  • 72,016
  • 6
  • 67
  • 89
  • 1
    The OP probably doesn't need it, but you could do `next(i, '')` in case the last element is an "+". – ekhumoro Oct 28 '20 at 16:55