python - 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']
解决方案
将[[(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']
推荐阅读
- javascript - 视频停止播放后,如何创建触发登录页面弹出的事件?
- drools - 在 Drools 规则引擎中使用列表
- javascript - 使用 Javascript 根据当前选择更改样式
- forms - Vue.js Phone 字段不是必需的,但如果为空则不让我提交
- python - 如何让scrapy网络爬虫框架保持跟踪链接?
- java - 如何使用注入类进行测试?Junit 返回 NPE
- php - 如何在将文件包含在 PHP 中之前安全地评估文件的内容
- microsoft-graph-api - Yammer 自定义共享按钮到外部链接
- image - 裁剪或屏蔽感兴趣区域之外的像素
- django - Django 简单模板标签问题