簡體   English   中英

Python 初學者 - 如何從列表中召回已刪除的項目

[英]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])

您還可以使用popinsert

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM