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

时间:2013-12-15 02:57:05

标签: python arrays call

QuarterlySales过程中调用DetermineRate时,每次循环时它只使用数组中的第一个数字。我想我已正确编入索引。此外,它只打印9个数字时应打印10个。

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的任何地方。

1 个答案:

答案 0 :(得分:1)

这是因为您使用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