![](/img/trans.png)
[英]beginner python text game, how do I remove a location from a list that has already been used
[英]Python Beginner - How do I recall the deleted items from a list
我是一个python初学者,我想知道一旦列表中的项目被替换,它能被召回吗?
Friends=["Jen","Lam","Sam","Song"]
print (Friends)
#replace a list item
Friends[0] = "Ken"
print (Friends)
如果我想说 Jen 在 python 中被 Ken 替换而不是直接写出print("Jen")
并使用变量,我应该如何写这行。
在替换之前跟踪Friends[0]
。
IE
friends=["Jen","Lam","Sam","Song"]
print(Friends)
replaced = friends[0]
friends[0] = "Ken"
print(replaced + " was replaced by " + friends[0])
您还可以使用pop
和insert
。
friends=["Jen","Lam","Sam","Song"]
print(friends)
replaced = friends.pop(0)
friends.insert(0, "Ken")
print(replaced + " was replaced by " + friends[0])
从来没听说过。 但是您可以制作一份列表的副本,然后通过从该列表中获取旧名称来使用它来将其改回原来的状态。
Friends=["Jen","Lam","Sam","Song"]
replaceName = Friends[0]
newName= "ken"
Friends [0] = newName
print(replaceName, " was replaced by ", newName)
print(Friends)
如果您想用列表中的“ken”替换名称,则必须将“jen”存储为变量。 像这样的东西:
replace = Friends[0]
Friends[0] = "ken"
在这两行之后,当您打印(Friends[0]) 时,它会返回“Ken”,但您可以打印(replace) 并打印“jen”
您还可以使用其他列表方法将 Ken .append 到列表中以在列表中包含两个名称。 该站点对所有不同的列表方法以及如何使用它们都非常有帮助! https://docs.python.org/3.9/tutorial/datastructures.html#the-del-statement
将“Jen”放在一个单独的变量中。
顺便说一下,我也是初学者:)
Friends = ["Jen", "Lam", "Sam", "Song"]
friend_to_delete = Friends[0]
print (Friends)
Friends[0] = "Ken"
print (Friends)
print(friend_to_delete, 'was replaced by', Friends[0])
非常简单的答案:
Friends=['Jen', 'Lam', 'Sam', 'Song']
print (Friends)
Friends.append('Ken') #This adds in the string('Ken') without directly altering the list
Friends.reverse() #This reverses the order in your list
Friends.remove('Jen') #This removes the string ('Jen') from your list
#Note you can also use Friends.pop(4) to remove the string 'Jen' since its reversed
print(Friends)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.