[英]python reverse function and boolean values error
i have written a function that produces a tuple of two lists from one list. 我写了一个函数,可以从一个列表中生成两个列表的元组。 one list contains the second, fourth and fifth values and the other list contains all the remaining values.
一个列表包含第二,第四和第五个值,另一个列表包含所有剩余的值。 i also have a condition that if reverse=True the values of the lists will be reversed when returned.
我也有一个条件,如果reverse = True,则返回时列表的值将被反转。
def seperate(x, reverse=False):
xs = []
ys = []
for i in range(0, len(x), 2):
xs.append(x[i])
ys.append(x[i + 1])
return (xs, ys)
if reverse is True:
x = xs.reverse()
y = ys.reverse()
return(x, y)
for some reason when reverse is True the lists are not being reversed, they are the same as when reverse is False 由于某些原因,当reverse为True时,列表不会被反转,它们与reverse为False时的列表相同
The reason reverse = True
is not working is that you have a return
statement right before the check: reverse = True
不起作用的原因是您在检查之前有一个return
语句:
return (xs, ys)
The code after the return
statement is never executed. return
语句后的代码永远不会执行。
Additionally, reverse()
reverses the list in place and returns None
, so x
and y
will end up being None
. 另外,
reverse()
在原处反转列表并返回None
,因此x
和y
最终将为None
。
Here is how both issues can be fixed: 解决这两个问题的方法如下:
if reverse:
xs.reverse()
ys.reverse()
return (xs, ys)
Finally, you could use slicing instead of an explicit loop to extract the odd/even elements: 最后,您可以使用切片而不是显式循环来提取奇/偶元素:
In [7]: x = [1, 2, 3, 4, 5, 6, 7, 8]
In [8]: x[::2]
Out[8]: [1, 3, 5, 7]
In [9]: x[1::2]
Out[9]: [2, 4, 6, 8]
reverse()
does not return any value. reverse()
不返回任何值。 It reverses the list in place. 它会在适当的位置反转列表。 So the reversed list is in
xs
and in ys
. 因此,反向列表在
xs
和ys
。
http://www.tutorialspoint.com/python/list_reverse.htm http://www.tutorialspoint.com/python/list_reverse.htm
Also you are returning before you execute the if
statement. 同样,您在执行
if
语句之前要返回。
return (xs, ys)
if reverse is True:
In functions, after return
everything is not working. 在函数中,
return
后一切都不起作用。 That's why your if
statement is not working. 这就是为什么您的
if
语句不起作用的原因。 It's making everything ineffective after return
. return
后一切都变得无效。 You can imagine it like; 您可以想像它;
def wr():
x="hey"
y="Hello"
return x
return y
print (wr())
Like this one, this function going to write only hey
, because it returned one time and other return y
is ineffective anymore. 像这个函数一样,该函数只写
hey
,因为它返回了一次,而其他return y
不再有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.