zoukankan      html  css  js  c++  java
  • 将元素移动到列表末尾

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

    方法#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']
  • 相关阅读:
    (转+原)python中的浅拷贝和深拷贝
    (原)torch7中添加新的层
    (原+转)ubuntu终端输出彩色文字
    (原)torch中显示nn.Sequential()网络的详细情况
    (原)python中使用plt.show()时显示图像
    eclipse 注释模板
    leetcode 11 最大盛水容器
    leetcode 9 回文数字
    leetcode8 字符串转整数
    利用Intent启动activity的例子
  • 原文地址:https://www.cnblogs.com/a00ium/p/15649589.html
Copyright © 2011-2022 走看看