Python 定义替换
如果我想写一个函数,目的是把列表 lst 中位置 pos 的元素替换成 item,那这个函数的主体部分应该怎么写呢?而且不能使用内置函数。
举个例子:
>>> def replace(lst, pos, item):
... mylist = [1,2,3]
...
>>> replace(mylist, 2, 'a')
>>> mylist
[1, 2, 'a']
我只是好奇而已。
2 个回答
1
operator.setitem
是你需要的东西。
import operator
mylist = [1,2,3]
operator.setitem(mylist, 2, 'a')
mylist
=> [1, 2, 'a']
正如 @tobias_k 提到的,这个和直接给列表赋值是一样的,后者更简单、更容易理解,也更符合 Python 的风格:mylist[2] = 'a'
2
你似乎在初始化 mylist
之前就把它传给了方法。然后你在方法里又创建了一个新的 mylist
,完全忽略了作为参数传入的那个列表。其实你应该这样做:
def replace(lst, pos, item):
lst[pos] = item
>>> mylist = [1,2,3]
>>> replace(mylist, 2, 'a')
>>> mylist
[1, 2, 'a']