Python 对于这样的函数,如何使用for循环?

Python 对于这样的函数,如何使用for循环?,python,for-loop,if-statement,bar-chart,Python,For Loop,If Statement,Bar Chart,如何使用“for”循环缩短代码。我只是不能使用这个函数 def f(year): if year==2017: plt.bar(["NA_Sales","JP_Sales","EU_Sales","Other_Sales"],abc.iloc[0,1:5]) elif year==2016: plt.bar([&qu

如何使用“for”循环缩短代码。我只是不能使用这个函数

def f(year):
    
        if year==2017:
            plt.bar(["NA_Sales","JP_Sales","EU_Sales","Other_Sales"],abc.iloc[0,1:5])
    
        elif year==2016:
             plt.bar(["NA_Sales","JP_Sales","EU_Sales","Other_Sales"],abc.iloc[1,1:5])
        elif year==2015:
             plt.bar(["NA_Sales","JP_Sales","EU_Sales","Other_Sales"],abc.iloc[2,1:5])
        elif year==2014:
             plt.bar(["NA_Sales","JP_Sales","EU_Sales","Other_Sales"],abc.iloc[3,1:5])
        elif year==2013:
             plt.bar(["NA_Sales","JP_Sales","EU_Sales","Other_Sales"],abc.iloc[4,1:5])
        elif year==2012:
             plt.bar(["NA_Sales","JP_Sales","EU_Sales","Other_Sales"],abc.iloc[5,1:5])
        elif year==2011:
             plt.bar(["NA_Sales","JP_Sales","EU_Sales","Other_Sales"],abc.iloc[6,1:5])
        elif year==2010:
             plt.bar(["NA_Sales","JP_Sales","EU_Sales","Other_Sales"],abc.iloc[7,1:5])

不要对循环使用
,使用数学:

def f(year):
    if year not in range(2010, 2018):
        return
    plt.bar(["NA_Sales","JP_Sales","EU_Sales","Other_Sales"],abc.iloc[2017-year,1:5])

year
iloc
下标的可变部分之间存在直接的线性关系——您可以将其表示为
2017年
,并在一行中完成整个函数(加上错误检查以捕获无效年份)。

首先,我建议您考虑一下您的功能的哪些方面是重复的,哪些部分是更改的。您的代码中似乎有两个主要的变化区域,与年份相关,也可能与某种索引号相关。是否可以将它们放入某种结构(可能是一个
dict
)中,然后进行迭代?您的代码的其他行(plt.bar()
部分)似乎彼此非常相似。也许这些部分可以浓缩?我喜欢你的分析,是的,也许字典是个好主意。我将尝试实现它哇,你让它看起来很简单!!