# 列表的创建

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

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(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]

>>> 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

from collections import Counter

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 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列表

(0)
(0)