首页 > 解决方案 > Python初学者 - 如何从列表中召回已删除的项目

问题描述

我是一个 python 初学者,我想知道一旦列表中的项目被替换,它可以被召回吗?

Friends=["Jen","Lam","Sam","Song"]
print (Friends)

#replace a list item 
Friends[0] = "Ken"
print (Friends)

如果我想说 Jen 在 python 中被 Ken 取代,而不是直接写出print("Jen")并使用变量,我应该怎么写。

标签: python

解决方案


Friends[0]在更换它之前跟踪它。

IE

friends=["Jen","Lam","Sam","Song"]
print(Friends)
replaced = friends[0]
friends[0] = "Ken"
print(replaced + " was replaced by " + friends[0])

您也可以使用popinsert

friends=["Jen","Lam","Sam","Song"]
print(friends)
replaced = friends.pop(0)
friends.insert(0, "Ken")
print(replaced + " was replaced by " + friends[0])

推荐阅读