將元素移動到列表末尾


列表的操作在日常編程中很常見。人們可能會遇到希望僅使用單襯紙執行的各種問題。一個這樣的問題可能是將列表元素移動到后面(列表末尾)。讓我們討論可以做到這一點的某些方法。

方法#1:使用append() + pop() + index()
通過組合這些功能,可以在一行中執行此特定功能。append 函數使用 index 函數提供的索引添加 pop 函數刪除的元素。 

# Python3 code to demonstrate  
# moving element to end 
# using append() + pop() + index()
  
# initializing list
test_list = ['3', '5', '7', '9', '11']
  
# printing original list 
print ("The original list is : " + str(test_list))
  
# using append() + pop() + index()
# moving element to end 
test_list.append(test_list.pop(test_list.index(5)))
  
# printing result
print ("The modified element moved list is : " + str(test_list))

 


輸出 : 原始列表為:['3', '5', '7', '9', '11']
修改后的元素移動列表為:['3', '7', '9', '11', '5']

 

方法#2:使用sort() + key = (__eq__)
sort 方法也可以用來完成這個特定的任務,在這個任務中,我們提供與我們希望移動的字符串相等的鍵,以便將它移到最后。

 
# Python3 code to demonstrate  
# moving element to end 
# using sort() + key = (__eq__)
  
# initializing list
test_list = ['3', '5', '7', '9', '11']
  
# printing original list 
print ("The original list is : " + str(test_list))
  
# using sort() + key = (__eq__)
# moving element to end 
test_list.sort(key = '5'.__eq__)
  
# printing result
print ("The modified element moved list is : " + str(test_list))

 


輸出 :
原始列表為:['3', '5', '7', '9', '11']
修改后的元素移動列表為:['3', '7', '9', '11', '5']


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM