我是python的新手,我正在尝试创建一个没有特定元素的列表副本。这就是我现在这样做的方式:
oldList[1,23,4,3,5,345,4]
newList = oldList[:]
del newList[3]
doSomthingToList(newList)
我想知道是否有更好的方法来做到这一点,而不是复制列表然后删除两行中的元素?
答案 0 :(得分:2)
>>> oldList = [1,23,4,3,5,345,4]
>>> newList = [x for i, x in enumerate(oldList) if i != 3] # by index
>>> newList
[1, 23, 4, 5, 345, 4]
>>> newList = [x for x in oldList if x != 4] # by value
>>> newList
[1, 23, 3, 5, 345]
答案 1 :(得分:2)
oldList[1,23,4,3,5,345,4]
newList = oldlist[:3] + oldList[4:]
doSomthingToList(newList)
答案 2 :(得分:0)
尝试使用'切片':
>>> oldList = [1, 2, 3, 4, 5]
>>> newList = oldList[:2] + [oldList[3:]
>>> newList
[1, 2, 4, 5]
答案 3 :(得分:0)
考虑使用内置函数filter
oldList = [1, 2, 3, 4, 5]
newList = filter(lambda number: number != 3, oldList)
# newList == [1,2,4,5]
filter
的参数是function, iterable
。它将您赋予它的函数应用于iterable的每个元素,并返回函数返回True的元素列表。