用字典中的值替换列表中的项目
我有一个词典。如果字典中的键在项目中,我想用相应的字典值替换列表的项目。例如,如果键'c'在“ CCC”之类的任何项目中,则将用相应的字典值替换“ CCC”。这是我的代码。
l=['0', 'CCC', '0', 'C', 'D', '0']
dic={"A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6, "G": 7, "U": 8}
for i in l:
for k, v in dic.items():
if k in i: i=str(v)
print(l)
我要得到的是:l = ['0','3','0','3','4','0']
,
但列表根本不会更改。我在这里做错了什么?
I have a dictionary. I want to replace an item of a list with corresponding dictionary value if a key in the dictionary is in the item. For example, if key 'C' is in any item like 'CCC', it will replace the 'CCC' with corresponding dictionary value. Here is my code.
l=['0', 'CCC', '0', 'C', 'D', '0']
dic={"A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6, "G": 7, "U": 8}
for i in l:
for k, v in dic.items():
if k in i: i=str(v)
print(l)
What I want to get is: l = ['0', '3', '0', '3', '4', '0']
but the list does not change at all. What am I doing wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
字典没有更改,因为当您在l:中使用
迭代列表时,创建了一个新对象
i
是从列表中获取值的。然后,您将更改i
的值,并使用字典中的适当值更改。但是,您只是更改对象i
的值。如果要从列表更改值,则应直接修改列表。您可以将更改为i:i = str(v)
如果k中的k中的k in:l.insert(l.index(i),v)
。这将首先找到列表中键的位置(索引),然后在该索引中插入关联的值。完整代码:
The dictionary isn't changing because when you are iterating the list with
for i in l:
a new objecti
is created taking values from the list. Then you are changing the value ofi
with the appropriate value from the dictionary. However, you are only changing the value of objecti
. If you want to change the values from the list you should modify the list directly. You can changeif k in i: i=str(v)
toif k in i: l.insert(l.index(i), v)
. This will find the location (index) of the key in the list first and then insert the associated value in that index.Full code:
根据您的注释,您可以使用此示例替换列表中的值
l
:打印:
Based on your comments you can use this example to replace the values in list
l
:Prints: