Python list.reverse 不返回列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4280691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
list.reverse does not return list?
提问by nakiya
The return object is named Nonefor list.reverse(). So this code fails when I call solution(k). Is there any way I can get around making a temporary? Or how should I do it?
返回的对象被命名None为list.reverse()。所以当我调用solution(k). 有什么办法可以解决临时问题吗?或者我应该怎么做?
fCamel = 'F'
bCamel = 'B'
gap = ' '
k = ['F', ' ', 'B', 'F']
def solution(formation):
return ((formation.index(bCamel) > (len(formation) - 1 - (formation.reverse()).index(fCamel))))
p.s. This is my first code in python. I thought it was functional.
ps 这是我在 python 中的第一个代码。我认为它是功能性的。
采纳答案by GWW
You can use reversed(formation)to return a reverse iterator of formation. When you call formation.reverse()it does an in place reversal of the list and returns None.
您可以使用reversed(formation)返回 的反向迭代器formation。当您调用formation.reverse()它时,它会原地反转列表并返回 None。
EDIT:
编辑:
I see what you are trying to do now, in my opinion it's easier to just do this with a list comprehension:
我明白你现在想要做什么,在我看来,通过列表理解来做到这一点更容易:
def solution(formation):
return len([k for k in formation[formation.index(bCamel)+1:] if k == fCamel]) == 0
This basically looks at all the elements after the first bCameland collects all the elements that have the value fCamel. If that list has a length == 0 you have a solution.
这基本上查看第一个之后的bCamel所有元素并收集所有具有 value 的元素fCamel。如果该列表的长度 == 0,则您有一个解决方案。
Here's a few examples:
下面是几个例子:
>>> k = ['F','F','B','B','F']
>>> solution(k)
False
>>> k = ['F','F','B','B','B']
>>> solution(k)
True
>>> k = ['F','F','B','F','F','B','B']
>>> solution(k)
False
>>>
回答by rbp
list.reverse reverses inplace. That is:
list.reverse 原地反转。那是:
>>> l = [1, 2, 3]
>>> l.reverse()
>>> l
[3, 2, 1]
Please consult the Python documentation, things like these are laid out there. You can also try the 'help' built-in:
请查阅Python 文档,那里有类似的内容。您还可以尝试内置的“帮助”:
help(l.reverse) Help on built-in function reverse:
reverse(...) L.reverse() -- reverse IN PLACE
help(l.reverse) 内置函数 reverse 的帮助:
反向(...)L.reverse() -反向到位
回答by Jason Baker
To build on GWW's answer, if you want this code to work as is you would just do list(reversed(formation)). If you really want to be able to use formation.reverse()instead, you would have to subclass list:
以 GWW 的回答为基础,如果您希望此代码按原样工作,您只需执行list(reversed(formation)). 如果您真的希望能够使用formation.reverse(),则必须子类化list:
>>> class ReversableList(list):
... def reverse(self):
... return list(reversed(self))
...
>>> x = ReversableList([1,2,3])
>>> x.reverse()
[3, 2, 1]
Whether or not this is advisable is another question of course.
当然,这是否可取是另一个问题。
回答by Morlock
Not super beautiful, but I did not find the equivalent in the precedent answers. If the speed or memory costs are low (the list is not very long or the operation not repeated a huge amount of times), this is pretty straight forward and even easier to read.
不是超级漂亮,但我没有在先例答案中找到等价物。如果速度或内存成本低(列表不是很长或操作没有重复大量的次数),这很简单,甚至更容易阅读。
import copy
fCamel = 'F'
bCamel = 'B'
gap = ' '
k = ['F', ' ', 'B', 'F']
def solution(formation):
rev_formation = copy.copy(formation)
rev_formation.reverse()
return ((formation.index(bCamel) > (len(formation) - 1 -
(rev_formation).index(fCamel))))
Cheers
干杯
回答by Leon
You can use slicing to return the reversed list:
您可以使用切片返回反向列表:
l[::-1]
回答by Cisco G
I just came across this problem and wanted to clarify some things for users new to python coming from a javascript background.
我刚刚遇到了这个问题,并想为来自 javascript 背景的 Python 新手澄清一些事情。
In javascript, a.reverse() reverses in place and also returns the array when called.
在 javascript 中, a.reverse() 原地反转并在调用时返回数组。
Javascript:
Javascript:
var a = [2, 3 ,4]
console.log(a.reverse())
// outputs [4, 3, 2]
console.log(a)
// outputs [4, 3, 2]
In python, a.reverse() reverses in place, but does not return the array.This is what caused confusion for me.
在 python 中,a.reverse() 原地反转,但不返回数组。这就是让我感到困惑的原因。
In python:
在蟒蛇中:
a = [2, 3, 4]
a.reverse()
print(a)
# outputs [4, 3, 2]
# can't do print(a.reverse())
回答by Alison Stuart
This doesn't provide a solution to the F _ B F pattern problem, but it does address the issue of python not returning a listwhen you use .reverse().
这并没有提供 F _ BF 模式问题的解决方案,但它确实解决了当您使用 .reverse() 时python 不返回列表的问题。
This is how I got around it:
我是这样解决的:
chars = ['a', '-', 'c']
chars2 = [] + chars
chars2.reverse()
totalChars = chars + chars2
totalChars returns a-cc-a, which is what I wanted, AND chars2 is a list, not a pointer to chars. Hope this helps.
totalChars 返回 a-cc-a,这是我想要的,并且 chars2 是一个列表,而不是指向字符的指针。希望这可以帮助。
回答by Tyshc
the following changes will be effective:
以下更改将生效:
NumSet={1,2,3,4,5,6,7,8,9,10}
NumList = list(NumSet)
NumList.reverse()
print(NumList)
avoid using the assignment operator after the initial assignment as lists are mutable types.
Using = operator with a method..(eg NumList = NumSet.reverse()) will cause the method to overwrite list with a blank, thereby effectively clearing the list. That's why list becomes a NoneType. Methods are functions and doesn't actually have its own value, thus the blank.
避免在初始赋值后使用赋值运算符,因为列表是可变类型。
在方法中使用 = 运算符..(例如 NumList = NumSet.reverse())将导致该方法用空白覆盖列表,从而有效地清除列表。这就是 list 变成 NoneType 的原因。方法是函数,实际上并没有自己的值,因此是空白。
回答by Abhiraam Eranti
I don't know if this works for you, but this works for me:
我不知道这是否适合你,但这对我有用:
list = [1,2,3]
print([list, list.reverse()][0])
The reason list.reverse() returns None is because the function doesn't return anything.
list.reverse() 返回 None 的原因是因为该函数不返回任何内容。
Using your code:
使用您的代码:
fCamel = 'F'
bCamel = 'B'
gap = ' '
k = ['F', ' ', 'B', 'F']
def solution(formation):
return ((formation.index(bCamel) > (len(formation) - 1 - ([formation, formation.reverse()][0]).index(fCamel))))
print(solution(k))
Hope this works for you!
希望这对你有用!
ps. Honestly, I have no idea why this works. I stumbled on it accidentally.
附:老实说,我不知道为什么会这样。我无意中发现了它。
回答by Stefan Pochmann
Title question is already answered, but for what you were really after:
标题问题已经得到解答,但对于您真正想要的:
Basically, this function should return true if all the 'F's are on the left hand side of the first 'B'
基本上,如果所有 'F' 都在第一个 'B' 的左侧,则此函数应返回 true
That's the same as there's no 'B' followed by an 'F'. Nice way to check this is with an iterator:
这与没有 'B' 后跟 'F' 相同。检查这一点的好方法是使用迭代器:
def solution(formation):
it = iter(formation)
return not (bCamel in it and fCamel in it)
Some advantages:
一些优点:
- Unlike every
formation.index(...)solution it doesn't crash if the searched value isn't there. - Takes only O(1) extra space (unlike the solutions making a reversed copy of the list).
- Touches every element at most onceand stops as soon as possible. Even has O(1) time best case (even with millions of elements, if the list starts with
['B', 'F',then it stops right there).
- 与每个
formation.index(...)解决方案不同,如果搜索值不存在,它不会崩溃。 - 仅占用 O(1) 额外空间(与制作列表反向副本的解决方案不同)。
- 最多接触每个元素一次并尽快停止。甚至有 O(1) 时间的最佳情况(即使有数百万个元素,如果列表以 开头,
['B', 'F',那么它就在那里停止)。

