How would I do following more efficiently without iterating twice through the zipped list:
x = [(item1['a'], item2) for item1, item2 in zip(foo, bar)]
y = [item2.replace(item1['b'], '') for item1, item2 in zip(foo, bar)]
How would I do following more efficiently without iterating twice through the zipped list:
x = [(item1['a'], item2) for item1, item2 in zip(foo, bar)]
y = [item2.replace(item1['b'], '') for item1, item2 in zip(foo, bar)]
Slightly less Pythonic:
x = []
y = []
for item1,item2 in zip(foo,bar):
x.append((item1['a'],item2))
y.append(item2.replace(item1['b'],''))
In general, you can use a generator expression to output multiple values as tuples and then zip the outputting sequence of tuples into individual sequences so that you can unpack them into separate variables.
So instead of, for example:
x = [i + 1 for i in lst]
y = [i + 2 for i in lst]
You can do:
x, y = zip(*((i + 1, i + 2) for i in lst))
In this case x and y will become tuples, however, so if you need x and y to be actual lists instead you can map the outputting sequence to the list constructor:
x, y = map(list, zip(*((i + 1, i + 2) for i in lst)))
So the statements in your question can be rewritten as:
x, y = map(list, zip(*(((item1['a'], item2), item2.replace(item1['b'], '')) for item1, item2 in zip(foo, bar))))