Range()函数不起作用

时间:2015-02-02 20:45:25

标签: python python-3.x built-in-types

我正在尝试编写一个程序,该程序将在网格上给出一个带有坐标点的二维列表(例如[[4, 7], [5, 6], [5, 2]]),并将返回在" walk"期间传递的所有点数。我们可以走对角线。

def pole(lista):
    passed = []   #List with all points passed
    before = lista[0]  #list with coordinates before
    for i in range(1,len(lista)):
        first = [list(range(before[0],lista[i][0]))]   # Lists that should have all points
        second = [list(range(before[1],lista[i][1]))]  # passed from point to point

        if(len(first) == 1):                  #If we do not go diagonal, one list will only have one number here,
            first = [before[0]*len(second)]   # but we need the same number of itmes,
        if(len(second) == 1):                 # so we do not get IndexOutOFRange error in next for   
            second = [before[1]*len(first)]
        #print(first,second)
        for j in range(len(first)):
            passed.append([first[j], second[j]])
        before = lista[i]
    return passed

我们使用示例列表作为输入。 [[4, 7], [5, 6], [5, 2]]

问题是输出错误,我不知道原因:

[[4, 7], [5, 6]]

输出应为:

[[4,7], [5,6], [5,5], [5,4], [5,3], [5,2]]

我认为这是范围功能的问题

2 个答案:

答案 0 :(得分:2)

那是因为range()函数不计算最后一个元素。

>>> x = [1,2,3,4]
>>> for i in range(len(x)):
    print (i)


0
1
2
3
>>> 

你看,4不在这里。你必须写for i in range(len(something)+1)

答案 1 :(得分:1)

我认为最简单的方法(假设你已经进口了scipy)倒退就是说 - >     我在scipy.linspace(10,8,3)