Python根据不同条件分配和绘制颜色时避免使用多个if语句

时间:2019-06-16 11:52:41

标签: python

我为字典中的不同对象分配了不同的颜色,并使用pyplot进行了绘制。我使用了多个if语句,但我希望避免这样做。什么是实现情节的最佳方法。这是我的代码:

for x,y in data.items():
    if x == 'coupe':
        plt.plot(y, ':', color = "yellow")
    if x == 'bike':
        plt.plot(y, ':', color = "black")
    if x == 'truck':
        plt.plot(y, ':', color = "blue")
    if x == 'van':
        plt.plot(y, ':', color = "white")
    if x == 'sedan':
        plt.plot(y, ':', color = "grey")

我得到了我想要的结果,但是我只知道会有更好的方法来实现这一目标。谢谢

1 个答案:

答案 0 :(得分:4)

由于所有的if语句都将测试字符串与plt.plot的输入值相关联,因此我们可以使用字典来存储这些对,然后更整齐地编写代码:

d = {'coupe':'yellow',
     'bike':'black',
     ...}
for x,y in data.items():
    if x in d:
        plt.plot(y, ':', color=d[x])