List 如何编写一个函数,在不创建新变量的情况下反转列表的顺序?
这就是我所尝试的:List 如何编写一个函数,在不创建新变量的情况下反转列表的顺序?,list,List,这就是我所尝试的: def reverse(given_list): """Reverses the order of a list (does not create a new object; simply reverses the order of the list. >>> r = ["Mario", "Bowser", "Luigi"] >>> reverse(r) >>> r ["Luigi
def reverse(given_list):
"""Reverses the order of a list (does not create a new object; simply reverses the order of the list.
>>> r = ["Mario", "Bowser", "Luigi"]
>>> reverse(r)
>>> r
["Luigi", "Bowser", "Mario"]
"""
given_list = sorted(given_list, key = given_list.index, reverse = True)
list_1 = ["a", "b", "c", "d"]
reverse(list_1)
print(list_1)
但是,运行此函数时,list_1
保持不变。如何让函数生成docstring中所示的输出?
请提供帮助。您需要根据您的方法返回给定的
列表
,并在打印
语句中使用该列表。例如:
def reverse(given_list):
given_list = sorted(given_list, key = given_list.index, reverse = True)
return given_list
list_1 = ["a", "b", "c", "d"]
list_1_reversed = reverse(list_1)
print(list_1_reversed)
将
list_1
作为方法的参数时,将创建并使用副本。所以这个问题是关于变量的范围。你可以在你最喜欢的关于python的书中或通过谷歌搜索找到变量范围的信息。你需要根据你的方法返回给定的列表,并在你的print
语句中使用它。例如:
def reverse(given_list):
given_list = sorted(given_list, key = given_list.index, reverse = True)
return given_list
list_1 = ["a", "b", "c", "d"]
list_1_reversed = reverse(list_1)
print(list_1_reversed)
将list_1
作为方法的参数时,将创建并使用副本。所以这个问题是关于变量的范围。您可以在最喜欢的python书籍中或通过谷歌搜索找到有关变量范围的信息。您使用的是什么编程语言?一定要把它作为一个标记。你用的是什么编程语言?一定要把它作为标签。