List comprehension combine 2 elements in nested list

dm2*_*111 1 python loops list-comprehension list nested-lists

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)
Run Code Online (Sandbox Code Playgroud)

sch*_*ggl 5

以下将起作用:

[[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']]
Run Code Online (Sandbox Code Playgroud)

如果最后一个元素可能是 a "+",则可以将默认值传递给next

next(i, "")
Run Code Online (Sandbox Code Playgroud)

以免出错。