刚刚复习了一下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
我做错什么了?在
您可以使用
//
运算符:当您升级到python3时,'
/
'运算符从整数除法改为实数除法。切换到“//
”运算符。在其他答案解释了为什么会出现错误。您需要使用
//
而不是/
(另外,仅对于记录,您需要给出list.insert
整数,而不是列表)。在但是,我想建议使用Explain Python's slice notation的不同方法:
这种方法应该比使用
list.pop
和list.insert
快得多。在作为证明,我编写了下面的脚本,将这两个方法与^{} 进行比较:
^{pr2}$结果如下:
如你所见,我提出的方法快了2秒。但是,如果你想验证我的测试,你可以运行更多的测试。在
相关问题 更多 >
编程相关推荐