Python Range()函数不工作
我正在尝试编写一个程序,该程序将给出一个二维列表,其中包含网格上的点坐标(例如,Python Range()函数不工作,python,python-3.x,built-in-types,Python,Python 3.x,Built In Types,我正在尝试编写一个程序,该程序将给出一个二维列表,其中包含网格上的点坐标(例如,[[4,7],[5,6],[5,2]),并将返回“行走”过程中经过的所有点。我们可以走对角线 def pole(lista): passed = [] #List with all points passed before = lista[0] #list with coordinates before for i in range(1,len(lista)): firs
[[4,7],[5,6],[5,2]
),并将返回“行走”过程中经过的所有点。我们可以走对角线
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]]
我认为这是range函数的问题,因为range()
函数不计算最后一个元素
>>> x = [1,2,3,4]
>>> for i in range(len(x)):
print (i)
0
1
2
3
>>>
你看,4
不在这里。您必须为范围内的i(len(something)+1)编写
我认为最简单的方法(假设您已经导入了scipy)是说->
对于scipy.linspace(10,8,3)中的i,这不是它的副本,为什么您将我的问题标记为副本?然后您能告诉我们如何调用该函数,以及您期望的输出是什么吗?我不清楚你想达到什么目的。我可能行动太快了;
[0]*len(秒)]
调用看起来像是在多个嵌套列表,就像在另一个规范问题中一样。对于问题顶部列出的示例,我看到([4],[7])
,([5],[6])
,([5],[4])
打印,以及[[4,7],[5,6],[5,4]
返回。几乎就在那里,你给函数什么输入,以产生错误的输出。我也不明白你想用输入做什么。谢谢,这解决了很多问题。但是如果我不能,因为如果是,例如从10到8+1是不正确的。@Krzys2014从10到8+1?如果你打算从10点开始,就不能从9点开始。我不明白你的意思,我的意思是,如果范围是10到8,那么+1不起作用,3在这里是什么意思?这是第一步吗?