python中好用的一些函数

版权声明:本文为博主原创文章,未经博主允许不得转载,如果有错误,欢迎指正,提前感谢。 https://blog.csdn.net/Quinlan_/article/details/78555785
  1. title() 将首字母大写
name  = ["tony","sam","andy"]
print(name[0].title())
	Tony
  • append()
    在列表末尾添加元素
name  = ["tony","sam","andy"]
>>> print(name[0].title())
Tony
>>> name.append('july')
>>> print(name)
['tony', 'sam', 'andy', 'july']
  • insert() 在列表的任何位置插入新元素。
    在列表的任何位置插入新元素,需要指定新元素的索引和值。
    括号内逗号前是要将元素插入的位置,逗号之后是需要插入的元素,并将列表中既有的每个元素都右移一个位置。
>>>name = ['tony', 'sam', 'andy', 'july']
>>> name.insert(1,'condy')
>>> print(name)
['tony', 'condy', 'sam', 'andy', 'july']
>>> 
  • del
    使用del可以删除已知列表中元素位置的元素。
['tony', 'condy', 'sam', 'andy', 'july']
>>> del name[4]
>>> print(name)
['tony', 'condy', 'sam', 'andy']
  • pop() 删除列表中元素后,还可以继续使用该元素的值。
    _pop()仅仅可以弹出列表中最后一个元素
>>> name
['tony', 'condy', 'sam', 'andy']
>>> poped_name = name.pop()
>>> print(name)
['tony', 'condy', 'sam']
>>> print(poped_name)
andy
而此时 poped_name 的值还是可以使用的,并没有将其完全删除 然而在name列表中,该元素已经被“弹出”。
 若想弹出/删除列表中任何位置的元素,只需要在pop()的括号中指定要删除的元素的索引即可。
  • remove() 根据元素的值来删除元素
    有时候你不晓得要删除的元素的索引是多少,但是你晓得要删除的值是多少,这时候可以用remove()来实现删除元素。
>>> name
['tony', 'condy', 'sam']
>>> name.remove("sam")
>>> name
['tony', 'condy']

此时要注意 remove()只删除第一个指定的值,如果要删除的值在列表中出现了多次,那么需要使用循环才能将这些值全部删除。

  • len() 确定列表的长度
    使用函数len可以快速获悉列表的长度
>>> name = [1,2,3,4,5,6,7]
>>> len (name)
7
  • sort() 对列表内元素进行永久性的排序
>>> num = [2,6,4,8,3,5,1,6]
>>> num.sort()
>>> num
[1, 2, 3, 4, 5, 6, 6, 8]
>>> char = ['a','f','c','d','b','e']
>>> char.sort()
>>> char
['a', 'b', 'c', 'd', 'e', 'f']

此时是按照升序的方法来进行的排序,如果想按照相反的来排序,则需要对sort()方法传递参数reverse = True.

>>> num
[1, 2, 3, 4, 5, 6, 6, 8]
>>> num.sort(reverse=True)
>>> num
[8, 6, 6, 5, 4, 3, 2, 1]
>>> char
['a', 'b', 'c', 'd', 'e', 'f']
>>> char.sort(reverse = True)
>>> char
['f', 'e', 'd', 'c', 'b', 'a']
  • sorted() 对列表进行临时排序
    临时排序,顾名思义,并不改变列表中元素的顺序,而是在显示列表中的元素时,对这些元素进行排序。
>>> print(num)
[8, 6, 6, 5, 4, 3, 2, 1]
>>> print(char)
['f', 'e', 'd', 'c', 'b', 'a']
>>> print(sorted(num))
[1, 2, 3, 4, 5, 6, 6, 8]
>>> print(sorted(char))
  • reverse() 反转列表元素的排列顺序,此时并非是对列表内元素进行排序,而是反转列表内的元素。
>>> num = [1,2,3,5,3]
>>> num.reverse()
>>> print(num)
[3, 5, 3, 2, 1]

猜你喜欢

转载自blog.csdn.net/Quinlan_/article/details/78555785