Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Bug?我';我做错了?_Python_Loops_Iteration - Fatal编程技术网

Python Bug?我';我做错了?

Python Bug?我';我做错了?,python,loops,iteration,Python,Loops,Iteration,我试图制作一个简单的迭代器,它在python中循环遍历一个列表并从列表中返回三个连续的数字,但我得到了一个非常奇怪的结果——只有当列表中的数字按升序排列时,代码才能正常工作 import itertools c=[0,1,2,3,0,5,6] counter=itertools.cycle(c) def func(x): if x==len(c)-1: return c[x],c[0],c[1] elif x==len(c)-2: return c

我试图制作一个简单的迭代器,它在python中循环遍历一个列表并从列表中返回三个连续的数字,但我得到了一个非常奇怪的结果——只有当列表中的数字按升序排列时,代码才能正常工作

import itertools
c=[0,1,2,3,0,5,6]
counter=itertools.cycle(c)
def func(x):
    if x==len(c)-1:
        return c[x],c[0],c[1]
    elif x==len(c)-2:
        return c[x],c[len(c)-1],c[0]
    else:
        return c[x],c[x+1],c[x+2]

for i in range(len(c)+2):
    print(func(next(counter)))
“我正在尝试制作一个简单的迭代器,它在python中循环遍历一个列表并从列表中返回三个连续的数字,但我得到了一个非常奇怪的结果——只有当列表中的数字按升序排列时,代码才能正常工作。Atom在第五个元组中打印以下内容。请帮忙

(0, 1, 2)
(1, 2, 3)
(2, 3, 0)
(3, 0, 5)
(0, 1, 2)
(5, 6, 0)
(6, 0, 1)
(0, 1, 2)
(1, 2, 3)

我相信你混淆了c值和指数。在
func
中,似乎期望传递索引,但实际上传递的是
c
中的值。注:
计数器
在c值上循环,而不是在索引上循环


另外请注意,在python中,您可以使用负索引,这样您就可以将
c[-1]
作为
c[len(c)-1]

的缩写来编写,如果您指定预期的输出应该是什么样子,这将非常有用。代码中不清楚您实际想要做什么。对于第五个值
x
0
。对于这种情况,您返回return
c[x],c[x+1],c[x+2]
。这就是
(0,1,2)
。您希望得到什么以及为什么?感谢您的回复,基本上,我想编写一段代码,用步骤1将一个数组循环成三个连续的数组值。C=[1,2,3,4]结果:(1,2,3),(2,3,4),(3,1,2),(1,2,3)等。它只返回结果中间的错误……是的,因为值匹配所有的索引,而第二个零表示消化,thnx Ivaylo。