2024-10-01 00:27:41 发布
网友
我是python新手,正在尝试创建一个没有特定元素的列表副本。我现在就是这样做的:
oldList[1,23,4,3,5,345,4] newList = oldList[:] del newList[3] doSomthingToList(newList)
我想知道是否有更好的更雄辩的方法来做到这一点,而不是复制列表,然后删除两行中的元素?你知道吗
用“切片”试试这个:
>>> oldList = [1, 2, 3, 4, 5] >>> newList = oldList[:2] + [oldList[3:] >>> newList [1, 2, 4, 5]
oldList[1,23,4,3,5,345,4] newList = oldlist[:3] + oldList[4:] doSomthingToList(newList)
使用list comprehension:
>>> 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]
用“切片”试试这个:
使用list comprehension:
相关问题 更多 >
编程相关推荐