当调用数组时,只使用第一个元素?

2024-06-28 19:39:49 发布

您现在位置:Python中文网/ 问答频道 /正文

当调用QuarterlySalesDetermineRate过程时,每次循环循环时,它只使用数组中的第一个数字。我想我已经把它编好索引了。而且当它应该打印出10个数字时,它只打印出9个数字。你知道吗

def FillQuarterlySales(QuarterlySales):
    #declare local variables
    Index = 0
    QuarterlySales = [0] * 10
    #Loading the array
    QuarterlySales = [21487, 22450, 7814, 12458, 4325, 9247, 18125, 5878, 16875, 10985]
    #Determine the quarterly sales based on the index
    return QuarterlySales

def DetermineRate(QuarterlySales):
    #declare local variables
    Rate = float()
    Index = 0
    Counter = 0
    Rates = [Index] * 9
    for Index in range (9):
        if QuarterlySales[Counter] < 5000:
            Rate = 0
        elif QuarterlySales[Counter] < 10000:
            Rate = 0.04
        elif QuarterlySales[Counter] < 15000:
            Rate = 0.08
        elif QuarterlySales[Counter] < 20000:
            Rate = 0.12
        else:
            Rate = 0.15
        #end if
        Rates[Index] = Rate
    #end for
    return Rates

没有错误代码,但当我打印出利率,以确保他们是正确的数组填充了相同的数字。在整个程序中,这种情况也发生在我调用QuarterlySales的任何地方。你知道吗


Tags: theindexreturnratelocaldefcounter数字
1条回答
网友
1楼 · 发布于 2024-06-28 19:39:49

这是因为您使用Counter来索引QuarterlySales,而不是Index。你知道吗

但是您的问题表明您对python缺乏经验,所以让我们尝试解决一些其他问题。你知道吗

Rates = [Index] * 9
...
QuarterlySales = [0] * 10

这看起来像是在尝试提前进行分配,这在python中几乎总是不必要的。当然,对于只有十个元素的列表来说,伤害大于帮助。你知道吗

而是这样做:

Rates = []
...
QuarterlySales = []

然后使用.append()方法将顺序数据元素添加到列表中。你知道吗

例如:

def DetermineRate(QuarterlySales):
    Rates = []
    for sales in QuarterlySales:
        if sales < 5000:
            Rates.append(0.)
        elif sales < 10000:
            Rates.append(0.04)
        elif sales < 15000:
            Rates.append(0.08)
        elif sales < 20000:
            Rates.append(0.12)
        else:
            Rates.append(0.15)
    return Rates

相关问题 更多 >