returning the list reversed

自古美人都是妖i 提交于 2019-12-04 06:53:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!