返回列表的副本,并反转第一个项目数

时间:2016-05-26 06:19:16

标签: python python-3.x

list1 = ['e', 'd', 'u', 'd']
list2 = ['m', 'o', 'b', 'b', 'e', 'd']

def reverse(list, number):
    number = (my_list[0])
    for i in my_list:
        my_list = str(my_list[number]) + str(i)
    return my_list

输出应为:

[d,u,d,e]
[b,o,m,b,e,d]

2 个答案:

答案 0 :(得分:0)

>>> list1 = ['e', 'd', 'u', 'd']
>>> list2 = ['m', 'o', 'b', 'b', 'e', 'd']
>>> def reverse(L, num):
...     return L[:num][::-1] + L[num:]
... 
>>> reverse(list1, 4)
['d', 'u', 'd', 'e']
>>> reverse(list2, 3)
['b', 'o', 'm', 'b', 'e', 'd']

仅使用循环:

>>> list1 = ['e', 'd', 'u', 'd']
>>> list2 = ['m', 'o', 'b', 'b', 'e', 'd']
>>> def reverse(L, num):
...     new_list=[]
...     for i in reversed(range(num)):
...          new_list+=L[i]
...     for i in range(num, len(L)):
...          new_list+=L[i]
...     return new_list
... 
>>> reverse(list1, 4)
['d', 'u', 'd', 'e']
>>> reverse(list2, 3)
['b', 'o', 'm', 'b', 'e', 'd']

答案 1 :(得分:0)

你可以尝试:

>>> def reverse(l,num):
    return [l[n] for n in range(num-1,-1,-1)] + l[num:]

>>> list1 = ['e', 'd', 'u', 'd']
>>> list2 = ['m', 'o', 'b', 'b', 'e', 'd']
>>> reverse(list1,4)
['d', 'u', 'd', 'e']
>>> reverse(list2,3)
['b', 'o', 'm', 'b', 'e', 'd']