首页 > 解决方案 > Iterate through multiple lists to apply the same changes to each

问题描述

As an example, let's say I have 3 different lists:

lst1 = ['a', 'b', 'c']
lst2 = ['d', 'e', 'f', 'g']
lst3 = ['h', 'i']

And I want to make the same changes to each one such that I can still call each list individually but with the new changes. So suppose I wanted to add a 'z' to every element in the above lists. I want to be able to call lst3 for example and get lst3 = ['hz', 'iz'].

I tried group each list into a list of lists: lists = [lst1, lst2, lst3]

Then applied my changes using [[(x + 'z') for x in z] for z in lsts]. But that just returns a list of lists.

I also tried using a for loop:

for each in lsts:
    each = [(x + 'z') for x in each] 

but when I call lst3 for example, it appears that the changes weren't done in-place.

Essentially I want to have the following output, so that each list is still separated by with the applied changes. Any insight into how I can achieve this?

lst1 = ['az', 'bz', 'cz']
lst2 = ['dz', 'ez', 'fz', 'gz']
lst3 = ['hz', 'iz']

标签: pythonlistlist-comprehension

解决方案


[[(x + "z") for x in z] for z in lists]返回的结果分配给lst1, lst2, lst3:

lst1 = ["a", "b", "c"]
lst2 = ["d", "e", "f", "g"]
lst3 = ["h", "i"]

lists = [lst1, lst2, lst3]

lst1, lst2, lst3 = [[(x + "z") for x in z] for z in lists]

print(lst1)
print(lst2)
print(lst3)

印刷:

['az', 'bz', 'cz']
['dz', 'ez', 'fz', 'gz']
['hz', 'iz']

推荐阅读