简体   繁体   English

在Python中反转列表

[英]Reversing a list in Python

def manualReverse(list):
    return list[::-1]

    def reverse(list):
        return list(reversed(list))   

list = [2,3,5,7,9]

print manualReverse(list)
print reverse(list)

I just started learning Python . 我刚开始学习Python Can anyone help me with the below questions? 任何人都可以帮助我解决以下问题吗?

1.How come list[::-1] returns the reversed list? 1.如何list[::-1]返回reversed列表?

2.Why does the second function throw me NameError: name 'reverse' is not defined ? 2.为什么第二个函数抛出我NameError: name 'reverse' is not defined

[::-1] is equivalent to [::1] , but instead of going left to right, the negative makes it go right to left. [::-1]相当于[::1] ,但不是从左到右,而是从右到左。 With a negative step of one, this simply returns all the elements in the opposite order. 如果为负一步,则只返回相反顺序的所有元素。 The whole syntax is called the Python Slice Notation . 整个语法称为Python Slice Notation

The reason why 'reverse' is not defined is because you did not globally define it. 'reverse' is not defined的原因是因为您没有全局定义它。 It is a local name in the manualReverse function. 它是manualReverse函数中的本地名称。 You can un-indent the function so it is a global function. 您可以取消缩进该函数,使其成为全局函数。

def manualReverse(list):
    return list[::-1]

def reverse(list):
    return list(reversed(list))   

By the way, it's never a good idea to name lists list . 顺便说一下,列出list永远不是一个好主意。 It will override the built-in type, including the function too, which you depend on ( list(reversed(list)) ) 它将覆盖内置类型,包括你依赖的函数( list(reversed(list))

list[::-1] utilizes a slice notation and returns all the elements but in reversed order. list[::-1]使用切片表示法并返回所有元素,但顺序相反。 Explain Python's slice notation Here is a detailed explanation with examples - it will answer this and more similar questions. 解释Python的切片符号下面是一个带有示例的详细解释 - 它将回答这个问题以及更多类似的问题。

Indentation of def reverse(list) makes it visible only inside manualReverse(list) . def reverse(list)缩进使其仅在manualReverse(list)可见。 If You unindent it will become visible globally. 如果你是unindent,它将在全球范围内变得可见。

Simply use the builtin function reversed 只需使用内置功能反转

>>> reversed(my_list)

See http://docs.python.org/2/library/functions.html?highlight=reversed#reversed http://docs.python.org/2/library/functions.html?highlight=reversed#reversed

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM