用字典中的值替换列表中的项目

发布于 2025-02-07 06:14:01 字数 427 浏览 0 评论 0原文

我有一个词典。如果字典中的键在项目中,我想用相应的字典值替换列表的项目。例如,如果键'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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

猫性小仙女 2025-02-14 06:14:01

字典没有更改,因为当您在l:中使用迭代列表时,创建了一个新对象i是从列表中获取值的。然后,您将更改i的值,并使用字典中的适当值更改。但是,您只是更改对象i的值。如果要从列表更改值,则应直接修改列表。您可以将更改为i:i = str(v) 如果k中的k中的k in:l.insert(l.index(i),v)。这将首先找到列表中键的位置(索引),然后在该索引中插入关联的值。

完整代码:

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: l.insert(l.index(k), v)

print(l)

The dictionary isn't changing because when you are iterating the list with for i in l: a new object i is created taking values from the list. Then you are changing the value of i with the appropriate value from the dictionary. However, you are only changing the value of object i. If you want to change the values from the list you should modify the list directly. You can change if k in i: i=str(v) to if 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=['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: l.insert(l.index(k), v)

print(l)
这样的小城市 2025-02-14 06:14:01

根据您的注释,您可以使用此示例替换列表中的值l

l = ["0", "CCC", "0", "C", "D", "0"]
dic = {"A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6, "G": 7, "U": 8}

out = [str(dic.get(list(set(v))[0], v)) for v in l]
print(out)

打印:

['0', '3', '0', '3', '4', '0']

Based on your comments you can use this example to replace the values in list l:

l = ["0", "CCC", "0", "C", "D", "0"]
dic = {"A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6, "G": 7, "U": 8}

out = [str(dic.get(list(set(v))[0], v)) for v in l]
print(out)

Prints:

['0', '3', '0', '3', '4', '0']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文