简体   繁体   English

调试Python代码

[英]Debugging Python code

After a few days I still cannot figure out how to make this work on python (not an experienced programmer). 几天后,我仍然无法弄清楚如何在python(不是经验丰富的程序员)上完成这项工作。 Here it is the code pasted and at the bottom, the expected result: 这是粘贴的代码,在底部是预期的结果:

color_list = ["red", "blue", "orange", "green"]
secuence = ["color", "price"]
car_list = []


def create_list(color_list, secuence, car_list):
    for num in range(len(color_list)):
        car_list.append = dict.fromkeys(secuence)
        car_list[%s]['color'] = color_list[%s] %num    
    return car_list

This is the result I want to achieve: 这是我想要实现的结果:

>> car_list
[{'color': 'red', 'price': None},{'color': 'blue', 'price': None},{'color': 'orange', 'price': None},{'color': 'green', 'price': None}]

You can do it all in one line for this particular scenario, assuming that 'color' and 'price' are constants. 假设'color''price'是常量,您可以针对此特定方案在一行中完成所有操作。

car_list = [{'color': color, 'price': None} for color in color_list]

See list comprehension - it's a powerful tool. 查看列表理解 - 它是一个强大的工具。


If you also had a list of prices, price_list , you could do something similar: 如果您还有价格清单price_list ,您可以做类似的事情:

car_list = [{'color': color, 'price': price} for color, price in zip(color_list, price_list)]

See the built in function zip() . 查看内置函数zip()


If the strings 'color' and 'price' are unknown at the time of execution (which I think is unlikely), you could do something similar to the following 如果字符串'color''price'在执行时是未知的(我认为不太可能),你可以做类似以下的事情

car_list = [{secuence[0]: color, secuence[1]: price} for color, price in zip(color_list, price_list)]

Try the following I'm not sure your can use key addressing not but here I have used it. 尝试以下我不确定你可以使用密钥寻址,但我在这里使用它。

def create_list(color_list, secuence, car_list): 
    for each in color_list:
        tmp = dict.fromkeys(secuence)
        tmp['color'] = each
        car_list.append(tmp)
    return car_list

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

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