简体   繁体   English

从字典中追加新列表

[英]appending new list from dictionary

What I want from the following code to link a color (in a new list) to a specific value, for example: if the value is a or A, the color should be always red and the hatch should be ".".我希望从以下代码中将颜色(在新列表中)链接到特定值,例如:如果值为 a 或 A,则颜色应始终为红色,并且阴影线应为“.”。 i tried the following code, it works fine but when i activate "else:" to add new values to the lists, it returns a long-mixed list.我尝试了以下代码,它工作正常,但是当我激活“else:”以向列表添加新值时,它返回一个长混合列表。

can someone help me out,please有人可以帮我吗,拜托

thanks a lot多谢

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

You used an unnecessary loop to iterate through the dictionary which was causing the main issue您使用了不必要的循环来遍历导致主要问题的字典

The following code works:以下代码有效:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM