将元素移动到列表末尾

列表的操作在日常编程中很常见。人们可能会遇到希望仅使用单衬纸执行的各种问题。一个这样的问题可能是将列表元素移动到后面(列表末尾)。让我们讨论可以做到这一点的某些方法。

方法#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']
原文地址:https://www.cnblogs.com/a00ium/p/15649589.html