首页 > 编程语言 > 详细

Python列表

时间:2020-09-29 23:23:21      阅读:64      评论:0      收藏:0      [点我收藏+]

列表的创建

使用赋值运算符直接创建列表

list1=[1,2,3,4]

list2=[‘a‘,‘b‘,‘c‘]

使用list函数创建列表

list() -> new empty list

list(iterable) -> new list initialized from iterable‘s items

 

>>> L = list(range(5))

>>> L

[0, 1, 2, 3, 4]

创建空列表

>>> L = list()

>>> L

[]

 

>>> L = []

>>> L

[]

 

创建定长空列表

>>> L = [None] * 5

>>> L

[None, None, None, None, None]

>>> len(L)

5

 

列表推导式

>>> L = [i for i in (1,2,3,4,5) if i>3]

>>> L

[4, 5]

 

>>> L = [i for i in (1,2,3,4,5) if i>6]

>>> L

[]

 

多维列表

以二维列表举例:二维列表就是,列表中的元素也是列表

>>> L = [[1,2,3,4,5],[6,7,8,9,0]]

>>> L

[[1, 2, 3, 4, 5], [6, 7, 8, 9, 0]]

>>> L[0]

[1, 2, 3, 4, 5]

>>> L[0][0]

1

 

字符串转换为列表

字符串的split方法

S.split(sep=None, maxsplit=-1) -> list of strings

 

sep为默认时,以空白字符作为分隔符

>>> s = ‘this is\tone\rtwo\nthree four‘

>>> s.split()

[‘this‘, ‘is‘, ‘one‘, ‘two‘, ‘three‘, ‘four‘]

 

指定分隔符

>>> s.split(‘.‘)

[‘www‘, ‘baidu‘, ‘com‘]

 

以空格作为分隔符和默认分隔符的对比

>>> a = ‘this is ok‘

>>> a.split(‘ ‘)

[‘this‘, ‘is‘, ‘ok‘]

>>> a = ‘this is ok‘

>>> a.split(‘ ‘)

[‘this‘, ‘is‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘ok‘]

>>> a.split()

[‘this‘, ‘is‘, ‘ok‘]

 

list方法(没啥用)

>>> s = ‘www.baidu.com‘

>>> list(s)

[‘w‘, ‘w‘, ‘w‘, ‘.‘, ‘b‘, ‘a‘, ‘i‘, ‘d‘, ‘u‘, ‘.‘, ‘c‘, ‘o‘, ‘m‘]

 

 

字符串特殊用法

str.center()

>>> print(‘main‘.center(20,‘=‘))

========main========

 

列表转换为字符串

join方法

>>> L = [‘www‘, ‘baidu‘, ‘com‘]

>>> S = ‘.‘.join(L)

>>> S

‘www.baidu.com‘

 

str方法(没啥用)

>>> L = [‘www‘, ‘baidu‘, ‘com‘]

>>> S = str(L)

>>> S

"[‘www‘, ‘baidu‘, ‘com‘]"

通用序列操作

len函数查询列表长度

>>> L

[[1, 2, 3, 4, 5], [6, 7, 8, 9, 0]]

>>> len(L)

2

>>> len(L[0])

5

sum函数求和,仅数值列表

>>> sum([1,2,3,4])

10

>>> sum([])

0

 

sorted函数排序,需要相同数据类型元素

sorted(iterable, /, *, key=None, reverse=False)

使用sorted函数后,原列表不变,需要生成一个新的列表

 

sorted(list,key,reverse)

 

>>> list

[1, 8, 5, 2, 6]

>>> sorted(list)

[1, 2, 5, 6, 8]

>>> list

[1, 8, 5, 2, 6]

+操作

实现的是列表的拼接,并没有修改列表,如果有需要,需要生成一个新的列表

 

>>> list1

[1, 2, 3, 4]

>>> list1+[‘5‘]

[1, 2, 3, 4, ‘5‘]

>>> list1

[1, 2, 3, 4]

>>> list2=list1+[‘5‘]

>>> list2

[1, 2, 3, 4, ‘5‘]

*操作

>>> L = [1,2,3]

 

>>> L*2

 

[1, 2, 3, 1, 2, 3]

>>> L = [1] *5

 

>>> L

 

[1, 1, 1, 1, 1]

切片

>>> L = [1,2,3,4,5,6,7,8]

 

单个下表取值

>>> L[0]

1

>>> L[-1]

8

切片,默认到结尾

>>> L[2:]

[3, 4, 5, 6, 7, 8]

 

切片,不包括右边界

>>> L[0:4]

[1, 2, 3, 4]

如果想包括右边界,可以写成L[0:4+1],但是有可能超出边界,可以挨个添加

>>> a = [L[i] for i in range(0,4+1)]

 

>>> a

 

[1, 2, 3, 4, 5]

 

>>> L[0:-1]

[1, 2, 3, 4, 5, 6, 7]

>>> L[0:-1:2]

[1, 3, 5, 7]

>>> L[-1:0]

[]

>>> L[-1:0:-1]

[8, 7, 6, 5, 4, 3, 2]

>>> L[-1:]

[8]

>>> L[-1::-1]

[8, 7, 6, 5, 4, 3, 2, 1]

>>> L[:]

[1, 2, 3, 4, 5, 6, 7, 8]

列表方法

>>> for i in dir(list):print(i)

 

append

clear

copy

count

extend

index

insert

pop

remove

reverse

sort

append在列表末尾添加新的对象

语法:

>>> help(list.append)

Help on method_descriptor:

 

append(...)

L.append(object) -> None -- append object to end

该方法无返回值,但是会修改原来的列表。

 

示例:

>>> L = [1,2,3]

>>> L.append(4)

>>> L

[1, 2, 3, 4]

>>> L.append([5,6,7])

>>> L

[1, 2, 3, 4, [5, 6, 7]]

clear 清空列表

语法:

>>> help(list.clear)

Help on method_descriptor:

 

clear(...)

L.clear() -> None -- remove all items from L

 

示例:

 

>>> L = [1,2,3,4]

>>> L.clear()

>>> L

[]

copy 浅拷贝列表

语法:

>>> help(list.copy)

Help on method_descriptor:

 

copy(...)

L.copy() -> list -- a shallow copy of L

 

示例:

 

  1. 等号拷贝

两个变量引用同一个对象,通过任意变量对对象进行的修改,都影响到另一个变量

 

>>> L1 = [[‘a‘,‘b‘],[‘c‘,‘d‘]]

>>> L2 = L1

>>> L2

[[‘a‘, ‘b‘], [‘c‘, ‘d‘]]

>>> L1[0][0] = ‘X‘

>>> L1

[[‘X‘, ‘b‘], [‘c‘, ‘d‘]]

>>> L2

[[‘X‘, ‘b‘], [‘c‘, ‘d‘]]

 

 

>>> L1 = [[‘a‘,‘b‘],[‘c‘,‘d‘]]

>>> L2 = L1

>>> L2

[[‘a‘, ‘b‘], [‘c‘, ‘d‘]]

>>> L1.pop()

[‘c‘, ‘d‘]

>>> L1

[[‘a‘, ‘b‘]]

>>> L2

[[‘a‘, ‘b‘]]

 

  1. copy浅拷贝

浅拷贝只拷贝最外层列表,对最外层列表元素的修改不互相影响,对内层列表元素的修改会相互影响

 

>>> L1 = [[‘a‘,‘b‘],[‘c‘,‘d‘]]

>>> L2 = L1.copy()

>>> L2

[[‘a‘, ‘b‘], [‘c‘, ‘d‘]]

>>> L1.pop()

[‘c‘, ‘d‘]

>>> L1

[[‘a‘, ‘b‘]]

>>> L2

[[‘a‘, ‘b‘], [‘c‘, ‘d‘]]

 

>>> L1 = [[‘a‘,‘b‘],[‘c‘,‘d‘]]

>>> L2 = L1.copy()

>>> L2

[[‘a‘, ‘b‘], [‘c‘, ‘d‘]]

>>> L1[0][0] = ‘x‘

>>> L1

[[‘x‘, ‘b‘], [‘c‘, ‘d‘]]

>>> L2

[[‘x‘, ‘b‘], [‘c‘, ‘d‘]]

 

3.[:]浅拷贝

>>> L1 = [[‘a‘,‘b‘],[‘c‘,‘d‘]]

>>> L2 = L1[:]

>>> L2

[[‘a‘, ‘b‘], [‘c‘, ‘d‘]]

>>> L1.pop()

[‘c‘, ‘d‘]

>>> L1

[[‘a‘, ‘b‘]]

>>> L2

[[‘a‘, ‘b‘], [‘c‘, ‘d‘]]

>>> L1[0][0] = ‘x‘

>>> L2

[[‘x‘, ‘b‘], [‘c‘, ‘d‘]]

count 统计某个元素在列表中出现的次数

语法:

>>> help(list.count)

Help on method_descriptor:

 

count(...)

L.count(value) -> integer -- return number of occurrences of value

 

示例:

>>> L = [1,2,3,1,‘a‘,1]

>>> L.count(1)

3

 

 

统计字符出现的个数或列表内出现的元素次数等也可以用 Counter。

一个 Counter 是一个 dict 的子类,用于计数可哈希对象。

 

from collections import Counter

c = Counter(‘sadasfas‘)

print(c)

 

输出结果:

Counter({‘s‘: 3, ‘a‘: 3, ‘d‘: 1, ‘f‘: 1})

extend 追加可迭代对象中的元素来扩展列表

语法:

>>> help(list.extend)

Help on method_descriptor:

 

extend(...)

L.extend(iterable) -> None -- extend list by appending elements from the iterable

 

示例:

1.当可迭代对象为字符串时

>>> L = [1,2,3]

>>> L.extend(‘abc‘)

>>> L

[1, 2, 3, ‘a‘, ‘b‘, ‘c‘]

2. 当可迭代对象为列表时

>>> L = [1,2,3]

>>> L.extend([4,5,‘a‘])

>>> L

[1, 2, 3, 4, 5, ‘a‘]

3. 当可迭代对象为字典时

>>> L = [1,2,3]

>>> L.extend({‘key1‘:‘vaule1‘,‘key2‘:‘vaule2‘})

>>> L

[1, 2, 3, ‘key1‘, ‘key2‘]

index 从列表中找出某个值第一个匹配项的索引位置

语法:

>>> help(list.index)

Help on method_descriptor:

 

index(...)

L.index(value, [start, [stop]]) -> integer -- return first index of value.

Raises ValueError if the value is not present.

 

示例:

>>> L = [1,2,3,4,1,2,3,4]

>>> L.index(2)

1

>>> L.index(2,2)

5

insert 将指定对象插入列表的指定位置

语法:

>>> help(list.insert)

Help on method_descriptor:

 

insert(...)

L.insert(index, object) -- insert object before index

 

示例:

>>> L = [1,2,3,4]

>>> L.insert(2,‘a‘)

>>> L

[1, 2, ‘a‘, 3, 4]

pop 根据位置删除元素(默认最后一个元素)

语法:

>>> help(list.pop)

Help on method_descriptor:

 

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.

 

示例:

 

>>> L = [1,2,3,4]

>>> L.pop()

4

>>> L

[1, 2, 3]

 

>>> L = [1,2,3,4]

>>> L.pop(2)

3

>>> L

[1, 2, 4]

 

删除不存在的位置会报错

>>> L = [1,2,3,4]

>>> L.pop(5)

Traceback (most recent call last):

File "<pyshell#56>", line 1, in <module>

L.pop(5)

IndexError: pop index out of range

remove 根据值删除元素

移除列表中某个值的第一个匹配项

语法:

>>> help(list.remove)

Help on method_descriptor:

 

remove(...)

L.remove(value) -> None -- remove first occurrence of value.

Raises ValueError if the value is not present.

 

示例:

>>> L = [1,2,3,4,2,3]

>>> L.remove(2)

>>> L

[1, 3, 4, 2, 3]

 

删除不存在的元素会报错

>>> L.remove(5)

Traceback (most recent call last):

File "<pyshell#54>", line 1, in <module>

L.remove(5)

ValueError: list.remove(x): x not in list

>>>

reverse 反向列表

语法:

>>> help(list.reverse)

Help on method_descriptor:

 

reverse(...)

L.reverse() -- reverse *IN PLACE*

 

示例:

>>> L = [1,2,3,4]

>>> L.reverse()

>>> L

[4, 3, 2, 1]

sort 对原列表进行排序

语法:

>>> help(list.sort)

Help on method_descriptor:

 

sort(...)

L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*

 

示例:

 

默认从小到大

>>> L = [3,6,2,8,0]

>>> L.sort()

>>> L

[0, 2, 3, 6, 8]

>>> L.sort(reverse = True)

>>> L

[8, 6, 3, 2, 0]

 

遍历列表

for循环

>>> for i in [1,2,3,4]:print(i)

 

1

2

3

4

enumerate()函数

使用for循环和enumerate()函数,可以带index输出

 

>>> for i in enumerate([‘a‘,‘b‘,‘c‘]):print(i)

 

(0, ‘a‘)

(1, ‘b‘)

(2, ‘c‘)

>>> for index,value in enumerate([‘a‘,‘b‘,‘c‘]):print(index,value)

 

0 a

1 b

2 c

递归打印列表

>>> def print_list(the_list):

    for i in the_list:

        if isinstance(i,list):print_list(i)

        else:print(i)

 

        

>>> L = [1,2,[‘a‘,‘b‘]]

>>> print_list(L)

1

2

a

b

Python列表

原文:https://www.cnblogs.com/jeancheng/p/13752282.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!