问题
i have this question:
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]]
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
?.
I've got this:
nums[::-1]
which does return nums
reversed.but i'm looking for a different way. probably looping?
Iv'e tried this:
def reverse3(nums):
return reversed(nums)
which returns: <list_reverseiterator object at 0x10151ff90>
#location?
回答1:
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]
回答2:
List has a built in reverse function
list.reverse()
so you could use
nums.reverse()
However, if you want to write your own function you would need to do a reverse iteration to another list.
Something like-
def revList(nums)
i = len(mums) -1
while i >= 0:
revNums[i] = nums.pop()
i = i - 1
return(revNums)
来源:https://stackoverflow.com/questions/26559920/returning-the-list-reversed