从字典中追加新的列表



我希望从以下代码中将颜色(在新列表中(链接到特定值,例如:如果值是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', '|', '.']

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

以下代码有效:

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', '|', '.']

最新更新