从字典追加新列表

时间:2020-04-30 06:32:15

标签: python list loops dictionary

我想从以下代码中将颜色(在新列表中)链接到特定值,例如:如果该值为a或A,则该颜色应始终为红色,而阴影应为“”。 。 我尝试了以下代码,但工作正常,但是当我激活“ else:”以向列表中添加新值时,它将返回一个长混合列表。

有人可以帮帮我吗,

非常感谢

dict1= {"A": ["red","."],"B": ["green","//"],"C": ["blue","o"],"D": ["Yellow","|"]}
name = ["g","B","c","d","a"]
color =[]
hatch=[]

for i in range(len(name)):
    for key, value in dict1.items():
        if name[i].upper() == key:
            name[i]=name[i].upper()
            color.append(value[0])
            hatch.append(value[1])
        # else:
        #     color.insert(i,"white")
        #     hatch.insert(i,"x")

print(name) # ['g', 'B', 'C', 'D', 'A']
print(color) # ['white','green', 'blue', 'Yellow', 'red']
print(hatch) # ['x','//', 'o', '|', '.']

1 个答案:

答案 0 :(得分:2)

您使用了不必要的循环来遍历导致主要问题的字典

以下代码有效:

dict1 = {"A": ["red", "."], "B": ["green", "//"], "C": ["blue", "o"], "D": ["Yellow", "|"]}
name = ["g", "B", "c", "d", "a"]
color = []
hatch = []

for i in range(len(name)):
    if name[i].upper() in dict1:
        key = name[i].upper()
        color.append(dict1[key][0])
        hatch.append(dict1[key][1])
    else:
        color.insert(i, "white")
        hatch.insert(i, "x")

print(name)  # ['g', 'B', 'C', 'D', 'A']
print(color)  # ['white','green', 'blue', 'Yellow', 'red']
print(hatch)  # ['x','//', 'o', '|', '.']
相关问题