list.reverse不返回列表? [英] list.reverse does not return list?
问题描述
对于 list.reverse()
,返回对象被命名为 None
。因此,当我调用 solution(k)
时,此代码失败。有什么办法可以解决临时问题吗?或者我该怎么做?
fCamel ='F'
bCamel ='B'
gap =''
k = ['F','','B','F']
def solution(格式):
return((formation .index(bCamel)>(len(formation)-1-(formation.reverse()).index(fCamel))))
ps这是我在Python中的第一个代码。你可以使用颠倒过来(格式)
>返回形式
的反向迭代器。当你调用 formation.reverse()
时,它会反转列表并返回None。
编辑:
我明白你现在想做什么,在我看来,这与列表理解:
$ pre $ def $ c $ def $ def b
return len([k for k in formation [ formation.index(bCamel)+1:] if k == fCamel])== 0
基本上查看了第一个 bCamel
之后的所有元素,并收集了所有具有值 fCamel
的元素。如果该列表的长度为== 0,您可以使用解决方案。
以下是一些示例:
>>> k = ['F','F','B','B','F']
>>>解决方案(k)
假
>>> k = ['F','F','B','B','B']
>>>解决方案(k)
真
>>> k = ['F','F','B','F','F','B','B']
>>>解决方案(k)
假
>>>
The return object is named None
for 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?
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.
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.
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 bCamel
and collects all the elements that have the value fCamel
. If that list has a length == 0 you have a solution.
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
>>>
这篇关于list.reverse不返回列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!