函数重复次数比预期的Python多

时间:2017-11-06 03:40:31

标签: python arrays list

我正在做一个python练习,我需要用x和y创建一个数组。以下是说明:

"""
Write a program which takes 2 digits, X,Y as input and generates a 2-
dimensional array. The element value in the i-th row and j-th column of the 
array should be i*j.

**Note** : i=0,1.., X-1; j=0,1,¡­Y-1.
**Example**
Suppose the following inputs are given to the program:
3,5
Then, the output of the program should be:
[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]] 
"""

这是我的代码:

def myfunc(x,y):
    newlist = []
    answer = 0
    icounter = 0
    jcounter = 0
    myarr = []
    for i in range(0, x+1):      
        for j in range(0,y+1):
            answer = jcounter * icounter
            newlist.append(answer)
            jcounter += 1
        jcounter = 0
        icounter += 1
        myarr.append(newlist)
        newlist = []
    print(myarr)

myfunc(3,5)

当我运行它时,我的答案是:

[[0,0,0,0,0],[0,1,2,3,4],[0,2,4,6,8],[0,3,6,9,12] ]

它里面应该只有3个列表,但它有4个。有谁知道为什么?

感谢任何帮助!

3 个答案:

答案 0 :(得分:0)

你最终得到范围(0,4)这是四个元素

答案 1 :(得分:0)

以下是您的解决方案的简化版本,其中包含错误修复:

def myfunc(x, y):
    myarr = []
    for i in range(x):
        row = []
        for j in range(y):
            row.append(i*j)
        myarr.append(row)

    return myarr

调用时为:

print(myfunc(3,5))

它产生:

[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]

为了将来参考,更高级的方法是使用列表推导。以下是等效的(并且更有效):

def myfunc(x, y):
    return [[i*j for j in range(y)] for i in range(x)]

答案 2 :(得分:0)

您的代码有四个数组而不是预期的三个数组的原因是因为您创建了范围参数(0,x + 1)而不是范围(x)。以下代码工作正常:

my_list = []

def function(x, y):
    for row in range(x):
        my_list.append([])
        for column in range(y):
            my_list[row].append(row * column)


function(3, 5)
print my_list

输出结果:

[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]