python数据类型之列表

python数据类型之列表

数据类型—列表list

特性:有序,可变的数据类型,可以存所有数据类型的任意多个数据,是可迭代的数据类型

官方帮助文档

Help on class dict in module builtins:
class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items
 |  
 |  Methods defined here:
 |  
 |  append(...)
 |      L.append(object) -> None -- append object to end
 |  
 |  clear(...)
 |      L.clear() -> None -- remove all items from L
 |  
 |  copy(...)
 |      L.copy() -> list -- a shallow copy of L
 |  
 |  count(...)
 |      L.count(value) -> integer -- return number of occurrences of value
 |  
 |  extend(...)
 |      L.extend(iterable) -> None -- extend list by appending elements from the iterable
 |  
 |  index(...)
 |      L.index(value, [start, [stop]]) -> integer -- return first index of value.
 |      Raises ValueError if the value is not present.
 |  
 |  insert(...)
 |      L.insert(index, object) -- insert object before index
 |  
 |  pop(...)
 |      L.pop([index]) -> item -- remove and return item at index (default last).
 |      Raises IndexError if list is empty or index is out of range.
 |  
 |  remove(...)
 |      L.remove(value) -> None -- remove first occurrence of value.
 |      Raises ValueError if the value is not present.
 |  
 |  reverse(...)
 |      L.reverse() -- reverse *IN PLACE*
 |  
 |  sort(...)
 |      L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None


创建列表

list() -> new empty list

| list(iterable) -> new list initialized from iterable's items

>>> a = [1]  # 这样创建列表,中间可以添加任何数据类型
>>> print(a, type(a))
[1] <class 'list'>

>>> b = list(123)  # 这样创建列表,必须是可迭代的数据类型,list(iterable)
Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    b = list(123)
TypeError: 'int' object is not iterable

list(iterable) -> new list initialized from iterable's items
>>> b = list('123')  # 可迭代的创建
>>> b
['1', '2', '3']

列表的方法

[ 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']


增加

L.append(元素) 追加(加到最后的位置)

L = L.append('james')(没有返回值)
L = ['a', 'b', 1, 2, ['c', 'd'],'james']


L.insert(索引,元素)在指定的索引位置插入元素

L.insert(2,"tony")(没有返回值)
L =['a', 'b', 'tony', 1, 2, ['c', 'd']]

扩展
extend(...)
    L.extend(iterable) -> None -- extend list by appending elements from the iterable
L.extend(L1)把L1扩展到L内,加在末尾,L发生改变,L1没有发生改变,会将L1拆分成最小元素加到L中。
>>> L = ['a', 'b', 1, 2, ['c', 'd']]
>>> L1 = ['a','c','james']
>>> L.extend(L1)
>>> L
['a', 'b', 1, 2, ['c', 'd'], 'a', 'c', 'james']

>>> L = ['a', 'b', 1, 2, ['c', 'd']]
>>> L.extend('abc')  # 可迭代的添加
>>> L
['a', 'b', 1, 2, ['c', 'd'], 'a', 'b', 'c']
>>> L = ['a', 'b', 1, 2, ['c', 'd']]
>>> L.extend(123)    # 数字不是可迭代的,所以报错
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
L.extend(123)
TypeError: 'int' object is not iterable

相加 L + L1,得到的结果是新开辟一块内存保存相加得到的数据,效率低,但是L没有发生改变

>>> L = ['a', 'b', 1, 2, ['c', 'd']]
>>> L1 = ['a','c','james']
>>> L2 = L + L1
>>> print(L, L1, L2)
['a', 'b', 1, 2, ['c', 'd']] ['a', 'c', 'james'] ['a', 'b', 1, 2, ['c', 'd'], 'a', 'c', 'james']

删除

L.remove(元素)删除指定元素,一次只能一个,元素不存在报错

L = ['a', 'b', 1, 2, ['c', 'd']]
L = L.remove(“a”)(没有返回值)
L =['b', 1, 2, ['c', 'd']]

L.pop(索引号)有索引是删除指定索引的元素,为空时默认删除最后一个。
L.pop(-1) =['c', 'd']  # 返回的是被删除的内容
>>> L = ['a', 'b', 1, 2, ['c', 'd']]
>>> L.pop()   # 索引为空的时候默认删除最后一个
['c', 'd']

清空
L.clear()
>>> L = ['a', 'b', 1, 2, ['c', 'd']]
>>> L.clear()
>>> L
[]

del全局删除
del L[索引]按索引删除元素
>>> L = ['a', 'b', 1, 2, ['c', 'd']]
>>> del L[2]
>>> L
['a', 'b', 2, ['c', 'd']]

del L[M:K]按照切片删除
>>> L = ['a', 'b', 1, 2, ['c', 'd']]
>>> del L[1:3]
>>> L
['a', 2, ['c', 'd']]

del L删除整个列表

>>> L = ['a', 'b', 1, 2, ['c', 'd']]
>>> del L
>>> L
Traceback (most recent call last):
File "<pyshell#118>", line 1, in <module>
L
NameError: name 'L' is not defined

修改

单个值,按索引赋值修改
>>> L = [1,2,'A','c']
>>> L[1] = 'james'
>>> L
[1, 'james', 'A', 'c']

多个值,切片形式,去除切片的元素,将赋值的元素迭代的添加
>>> L = [1,2,'A','c']
>>> L[0:2] = 'james'
>>> L
['j', 'a', 'm', 'e', 's', 'A', 'c']

>>> L[0:2] = 1  # 必须等于一个可迭代的类型
Traceback (most recent call last):
  File "<pyshell#39>", line 1, in <module>
    L[0:2] = 1
TypeError: can only assign an iterable
>>> L[0:2] = [1]  # 切片赋值的原数据和赋值的数据不相等时,数据个数会变少
>>> L
[1, 'A', 'c']

查询

通过索引查询操作;正向递增,反向递减,从左往右从0开始,最末尾的为-1。
L = ['a', 'b', 1, 2, ['c', 'd']]
      0    1   2  3       4
L[1] = ‘b’
L[4] = ['c', 'd']

L[索引号]就可以取出所对应的值

切片:L[M:N:K]M和N为索引号,K为步长。从M到N(包括M不包括N)根据步长K取值。
M和N缺失时代表至开头和至结尾(包括最后一个值)
K为负数时代表从右往左开始取值。(当K为负值时,M>N)
>>> L = ['a', 'b', 1, 2, ['c', 'd']]
>>> L[:-2:2]
['a', 1]

>>> L = ['a', 'b', 1, 2, ['c', 'd']]
>>> L[-1:-3:-1]
[['c', 'd'], 2]

a= [1,2,3,4,5,'a','c',11,23,22,55]
print(a[10:0:-1])    
>>>[55, 22, 23, 11, 'c', 'a', 5, 4, 3, 2]
a= [1,2,3,4,5,'a','c',11,23,22,55]
print(a[0:10:-1])    # K为负值时,M<N,返回一个空列表
>>>[]

列表的其他方法

L.index(元素)返回元素的索引
>>> L = ['a', 'b', 1, 2, ['c', 'd']]
>>> L.index('b')
1

L.count(元素)返回元素在L中的个数(如果有多个相同元素,找到的是第一个元素的索引)
>>> L = ['a', 'b', 1, 2, ['c', 'd']]
>>> L.count('a')
1

sort(...)
    L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
    
L.sort(reverse=False)排序,把列表中的元素按照ASCII码表排序,只能同种数据类型排序,否则报错,默认为False,从小到大,reverse=True,从大到小
>>> L = ['a', 'b', 1, 2, ['c', 'd']]
>>> L.sort()
Traceback (most recent call last):
  File "<pyshell#98>", line 1, in <module>
    L.sort()
TypeError: '<' not supported between instances of 'int' and 'str'

>>> L = ['c', 'z', 'a', 'g']
>>> L.sort()  # 没有返回值,执行完反序后直接赋值给L
>>> L
['a', 'c', 'g', 'z']


reverse(...)
    L.reverse() -- reverse *IN PLACE*
L.reverse()反序,把列表中的元素反序,没有返回值,执行完反序后直接赋值给L
>>> L = ['a', 'b', 1, 2, ['c', 'd']]
>>> L.reverse()
>>> L
[['c', 'd'], 2, 1, 'b', 'a']

len(L)列表里面元素的个数
>>> L = ['a', 'b', 1, 2, ['c', 'd']]
>>> print(len(L))

列表的循环

遍历循环列表,打印列表的元素
>>> L = ['a', 'b', 1, 2, ['c', 'd']]
>>> for i in L:
    print(i)    
a
b
1
2
['c', 'd']


遍历循环列表,打印列表的索引以及对应的元素值
>>> L = ['a', 'b', 1, 2, ['c', 'd']]
>>> for index,i in enumerate(L):
    print(index,i)    
0 a
1 b
2 1
3 2
4 ['c', 'd']

列表的深浅copy

1.赋值运算(两个列表指向的是同一个内存地址,共享里面的所有元素,一个改变另一个也改变)

l1 = [1,2,3,['barry','alex']]
l2 = l1

l1[0] = 111
print(l1)  # [111, 2, 3, ['barry', 'alex']]
print(l2)  # [111, 2, 3, ['barry', 'alex']]

l1[3][0] = 'wusir'
print(l1)  # [111, 2, 3, ['wusir', 'alex']]
print(l2)  # [111, 2, 3, ['wusir', 'alex']]

2.浅copy(列表里面的第一层是独立的,但是列表里面的子列表里面的元素又是共享的)

l1 = [1,2,3,['barry','alex']]

l2 = l1.copy()
print(l1,id(l1))  # [1, 2, 3, ['barry', 'alex']] 2380296895816
print(l2,id(l2))  # [1, 2, 3, ['barry', 'alex']] 2380296895048
l1[1] = 222
print(l1,id(l1))  # [1, 222, 3, ['barry', 'alex']] 2593038941128
print(l2,id(l2))  # [1, 2, 3, ['barry', 'alex']] 2593038941896
 
l1[3][0] = 'wusir'
print(l1,id(l1[3]))  # [1, 2, 3, ['wusir', 'alex']] 1732315659016
print(l2,id(l2[3]))  # [1, 2, 3, ['wusir', 'alex']] 1732315659016

3.深拷贝deepcopy(需要调用python的第三方工具,copy模块,这样得到的两个列表是完全独立的)

import copy
l1 = [1,2,3,['barry','alex']]
l2 = copy.deepcopy(l1)

print(l1,id(l1))  # [1, 2, 3, ['barry', 'alex']] 2915377167816
print(l2,id(l2))  # [1, 2, 3, ['barry', 'alex']] 2915377167048

l1[1] = 222
print(l1,id(l1))  # [1, 222, 3, ['barry', 'alex']] 2915377167816
print(l2,id(l2))  # [1, 2, 3, ['barry', 'alex']] 2915377167048

l1[3][0] = 'wusir'
print(l1,id(l1[3]))  # [1, 222, 3, ['wusir', 'alex']] 2915377167240
print(l2,id(l2[3]))  # [1, 2, 3, ['barry', 'alex']] 2915377167304
原文地址:https://www.cnblogs.com/james201133002/p/9437031.html