pop()lis中的两个元素

2024-06-28 11:34:17 发布

您现在位置:Python中文网/ 问答频道 /正文

刚刚复习了一下Python类,发现我忘了怎么做。在

def outsideIn2(lst):

'''(list)->list

Returns a new list where the middle two elements have been
removed and placed at the beginning of the result. Assume all lists are an even
length

>>> outsideIn2(['C','a','r','t','o','n']) 
['r','t','C','a','o','n'] # rt moves to front
>>> outsideIn2(['H','i']) 
['H','i'] # Hi moves to front so output remains the same.
>>> outsideIn2(['B','a','r','b','a','r','a',' ','A','n','n','e']) 
['r','a','B','a','r','b,','a',' ','A','n','n','e'] # ra moves to front.
'''
length = len(lst)
middle1 = lst.pop((len(lst) / 2) - 1)
middle2 = lst.pop((len(lst) / 2) + 1)

lst.insert([0], middle1)
lst.insert([1], middle2)                  

return lst

我得到了这个错误:

middle1 = lst.pop((len(lst) / 2) - 1)

TypeError: integer argument expected, got float

我做错什么了?在


Tags: thetolendefpoplengthlistreturns
3条回答

您可以使用//运算符:

middle1 = lst.pop((len(lst) // 2) - 1)

当您升级到python3时,'/'运算符从整数除法改为实数除法。切换到“//”运算符。在

其他答案解释了为什么会出现错误。您需要使用//而不是/(另外,仅对于记录,您需要给出list.insert整数,而不是列表)。在


但是,我想建议使用Explain Python's slice notation的不同方法:

def outsideIn2(lst):
    x = len(lst)//2
    return lst[x-1:x+1]+lst[:x-1]+lst[x+1:]

这种方法应该比使用list.poplist.insert快得多。在

作为证明,我编写了下面的脚本,将这两个方法与^{}进行比较:

^{pr2}$

结果如下:

6.255111473664949
4.465956427423038

如你所见,我提出的方法快了2秒。但是,如果你想验证我的测试,你可以运行更多的测试。在

相关问题 更多 >