list.reverse 不返回列表? [英] list.reverse does not return list?

查看:14
本文介绍了list.reverse 不返回列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

返回对象被命名为 None 用于 list.reverse().所以当我调用 solution(k) 时,这段代码失败了.有什么办法可以解决临时问题吗?或者我该怎么做?

fCamel = 'F'b骆驼 = 'B'间隙 = ' 'k = ['F', ' ', 'B', 'F']定义解决方案(编队):返回 ((formation.index(bCamel) > (len(formation) - 1 - (formation.reverse()).index(fCamel))))

附言这是我在 python 中的第一个代码.我认为它是实用的.

解决方案

您可以使用 reversed(formation) 返回 formation 的反向迭代器.当您调用 formation.reverse() 时,它会原地反转列表并返回 None.

我明白你现在想要做什么,在我看来,使用列表理解更容易做到这一点:

def 解决方案(编队):return len([k for k information[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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆