问题描述
我有这个问题:
编写一个函数reverse3(nums),该函数接受一个长度为3的整数列表,称为nums
,并返回一个具有相反顺序的元素的新列表,因此[1、2、3]变为[3, 2,1].
Write a function reverse3(nums) that takes a list of ints of length 3 called nums
and returns a new list with the elements in reverse order, so [1, 2, 3] becomes [3, 2, 1].
我通过以下方式解决了该问题:
i solved it by:
def reverse3(nums):
return [nums[2]] + [nums[1]] + [nums[0]]
但是,答案是直截了当的.我的主要问题是,当我不知道nums
中有多少个整数时,如何反转nums
?
however, the answer is straight foward. My main question, how do i get nums
reversed, when i don't know how many ints there are in nums
?.
我有这个:nums[::-1]
确实返回nums
反转.但是我正在寻找不同的方式.可能会循环吗?
I've got this:nums[::-1]
which does return nums
reversed.but i'm looking for a different way. probably looping?
我尝试过:
def reverse3(nums):
return reversed(nums)
返回:<list_reverseiterator object at 0x10151ff90>
#location?
which returns: <list_reverseiterator object at 0x10151ff90>
#location?
推荐答案
返回一个迭代器.如果要获取列表对象,请使用 list
:
reversed
returns an iterator. If you want to get a list object, use list
:
>>> def reverse3(nums):
... return list(reversed(nums))
...
>>> reverse3([4,5,6])
[6, 5, 4]
这篇关于反向返回列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!