python 数据结构--List(列表)

1.1 列表与序列共有的操作补充

有关序列的操作,如索引、分片、相加、乘法等都适用于列表

list1 = [1,2,3,4,5]
list2 = [5,6,7,8,9]

1.1.1 索引

list1[2]  
3

1.1.2 分片

list1[1:4]    #分片操作,分片取值类似[a,b),默认步长为1,正序遍历
[2, 3, 4]
list1[1:4:2]
[2, 4]
list1[5::-1]    #逆序遍历
[5, 4, 3, 2, 1]

1.1.3 相加

list1 + list2 #列表相加
[1, 2, 3, 4, 5, 5, 6, 7, 8, 9]

1.1.4 乘法

list1 * 2   #列表乘法
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

1.1.5 成员资格

2 in list1   #成员资格
True
10 in list1
False

1.2 列表有序列没有的方法

这些方法的作用主要都是更新列表,有元素赋值、增加元素、删除元素、分片赋值等。

a = [1,2,3,4,5,6,7,8,9,10]
a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

1.2.1 元素赋值

a[1] = 'q'    
a
[1, 'q', 3, 4, 5, 6, 7, 8, 9, 10]
type(a)
list
type(a[1])
str

1.2.2 增加元素

listname = ['Jack', 'nick']
listname
['Jack', 'nick']
listname.append('James')  #用append()函数在列表末尾追加元素
listname
['Jack', 'nick', 'James']

1.2.3 删除元素

num = [1,2,3,4]
num
[1, 2, 3, 4]
del num[2] # 删除列表元素
num
[1, 2, 4]

1.2.4 分片赋值

a = list('abcd')   #list()函数将字符序列转换为列表
a
['a', 'b', 'c', 'd']
show = list('hi,student.')
show
['h', 'i', ',', 's', 't', 'u', 'd', 'e', 'n', 't', '.']
show[3:] = list('teacher')  # 分片赋值
show
['h', 'i', ',', 't', 'e', 'a', 'c', 'h', 'e', 'r']
boil = list('女排夺得冠军')
boil
['女', '排', '夺', '得', '冠', '军']
boil[4:4] = list('2016年奥运会')
boil
['女', '排', '夺', '得', '2', '0', '1', '6', '年', '奥', '运', '会', '冠', '军']

1.3 嵌套列表

listone = ['a', 'b', 'c']
listtwo = ['1', '2', '3']
mix = [listone, listtwo]
mix[0]
['a', 'b', 'c']
mix[1]
['1', '2', '3']

1.4 列表方法

列表有count、index、sort等常用的方法

1.4.1 append() 方法

a = [1,2,3,4]
a.append(5)
a
[1, 2, 3, 4, 5]

1.4.2 count() 方法

count()方法用于统计某个元素在列表中出现的次数。

a = [1,2,3,4,3,4,1,2,1,1,1]
a.count(1)
5

1.4.3 extend() 方法

 extend()方法用于在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)。extend()方法的语法如下:list.extend(seq)此语法中,list代表被扩展的列表,seq代表需要追加到list中的元素列表。

fruit = ['apple', 'orange', 'pear']
vegetables = ['tomato', 'potato', 'fish']
food = []
food
food.extend(fruit)
food
food.extend(vegetables)
food
['apple', 'orange', 'pear', 'tomato', 'potato', 'fish']
fruit = ['apple', 'orange', 'pear']
vegetables = ['tomato', 'potato', 'fish']
fruit+ vegetables  
['apple', 'orange', 'pear', 'tomato', 'potato', 'fish']
fruit
['apple', 'orange', 'pear']

extend()方法和序列相加的主要区别是:extend()方法修改了被扩展的序列, 原始的连接操作会返回一个全新的列表,序列相加,返回的是一个包含a和b副本的新列表,而不会修改原始的变量。

# 可使用 fruit[len(fruit):] = vegetables   
# 输出结果和使用extend()方法一样,不过看起来没有extend()方法易懂,因此不会选择这个方案。
fruit = ['apple', 'orange', 'pear']
vegetables = ['tomato', 'potato', 'fish']
fruit[len(fruit):] = vegetables
fruit
['apple', 'orange', 'pear', 'tomato', 'potato', 'fish']

1.4.4 index() 方法

index()方法用于从列表中找出某个值第一个匹配项的索引位置。index()方法的语法如下:list.index(obj)此语法中,list代表列表,obj代表查找的对象。

a = [1,2,3,4,5,1]
a.index(1)

# index(6)

#ValueError                                Traceback (most recent call last)
#<ipython-input-43-a25d145b236e> in <module>()
#      1 a = [1,2,3,4,5,1]
#----> 2 a.index(6)
#
#ValueError: 6 is not in list

0

1.4.5 insert() 方法

insert()方法用于将对象插入列表。insert()方法的语法如下:list.insert(index,obj)此语法中,list代表列表,index代表对象obj需要插入的索引位置,obj代表要插入列表中的对象。

num = [1,2,3,4]
num.insert(1,1.5)
num
[1, 1.5, 2, 3, 4]

1.4.6 pop() 方法

pop()方法用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。pop()方法的语法如下:list.pop(obj=list[-1])此语法中,list代表列表,obj为可选择的参数,代表要移除列表元素的对象。

num = ['1','2','3','4','5']
num.pop() #不传参数默认返回最后一个元素
'5'
num = ['1','2','3','4','o']
num.pop(4) #移出编号为4的元素
'o'
print("元素移出后,列表为:",num)
元素移出后,列表为: ['1', '2', '3', '4']

pop方法是唯一既修改列表又返回元素值(除了None外)的列表方法。使用pop方法可以实现一种常见的数据结构

stack = []
stack.append(1)
print("入栈后列表为:",stack)
入栈后列表为: [1]
stack.append(2)
print("入栈后列表为:",stack)
入栈后列表为: [1, 2]
print("出栈元素:", stack.pop(1))
出栈元素: 2
print(stack)
[1]

1.4.7 remove() 方法

remove()方法用于移除列表中某个值的第一个匹配项。remove()方法的语法如下:list.remove(obj)此语法中,list代表列表,obj为列表中要移除的对象。

num = [1,2,3,4,5,1,2,3,4,5]
num.remove(5)
num
[1, 2, 3, 4, 1, 2, 3, 4, 5]

1.4.8 reverse() 和 reversed()方法

reverse()方法用于反向列表中的元素。reverse()方法的语法如下:list.reverse()此语法中,list代表列表,该方法不需要传入参数。

poem = ["举杯消愁愁更愁","抽刀断水水更流"]
poem.reverse()
poem
['抽刀断水水更流', '举杯消愁愁更愁']

如果需要对一个序列进行反向迭代,那么可以使用reversed函数。这个函数并不返回列表,而是返回一个迭代器(Iterator)对象(该对象在后面会详细介绍),可以通过list函数把返回的对象转换为列表

poem = ["举杯消愁愁更愁","抽刀断水水更流"]
list(reversed(poem))
['抽刀断水水更流', '举杯消愁愁更愁']

1.4.9 sort() 和 sorted()方法

sort()方法用于对原列表进行排序,如果指定参数,就使用参数指定的比较方法进行排序。sort()方法的语法如下:list.sort(func)此语法中,list代表列表,func为可选参数。如果指定该参数,就会使用该参数的方法进行排序。

num = [1,3,5,6,2,4,8,7]
num.sort()
num
[1, 2, 3, 4, 5, 6, 7, 8]
num = [1,3,5,6,2,4,8,7]
n = num
print("副本列表为:",n)
n.sort()
print("副本排序为:",n)
print("原来列表为:", num) # 也随着副本排序变化了,不是想要的结果
副本列表为: [1, 3, 5, 6, 2, 4, 8, 7]
副本排序为: [1, 2, 3, 4, 5, 6, 7, 8]
原来列表为: [1, 2, 3, 4, 5, 6, 7, 8]
num = [1,3,5,6,2,4,8,7]
n = num[:]
print("副本列表为:",n)
n.sort()
print("副本排序为:",n)
print("原来列表为:", num) # 原来的数据不随副本排序而改变
副本列表为: [1, 3, 5, 6, 2, 4, 8, 7]
副本排序为: [1, 2, 3, 4, 5, 6, 7, 8]
原来列表为: [1, 3, 5, 6, 2, 4, 8, 7]

由上面的执行结果可以看到,若不将原列表(如列表num)分片后赋值给另一个变量(如n),则两个列表都会被排序,这样简单的赋值后,两个列表都指向同一个列表。由此提醒进行该操作时要记得对原列表分片。

如reverse方法一样,sort方法也有一个有同样功能的函数——sorted函数。该函数可以直接获取列表的副本进行排序。

sorted('123')
['1', '2', '3']
sorted('uoiea')
['a', 'e', 'i', 'o', 'u']
num = [5,6,1,3,4,2]
n = sorted(num)
print("原来列表数据:", num)
print("副本排序数据:", n)
原来列表数据: [5, 6, 1, 3, 4, 2]
副本排序数据: [1, 2, 3, 4, 5, 6]

1.4.10 clear()方法

clear()方法用于清空列表,类似于del a[:]。clear()方法的语法如下:list.clear()此语法中,list代表列表,不需要传入参数。

a = [1,2,3,4,5]
a.clear()
a
[]

1.4.11 copy()方法

copy()方法用于复制列表,类似于a[:]。copy()方法的语法如下:list.copy()此语法中,list代表列表,不需要传入参数。

num = list('1234567')
copynum = num.copy()
copynum
['1', '2', '3', '4', '5', '6', '7']

1.4.12 高级排序

如果希望元素按特定方式进行排序(不是sort方法默认的按升序排列元素),就可以自定义比较方法。sort方法有两个可选参数,即key和reverse。要使用它们,就要通过名字指定,我们称之为关键字参数。

stringlist = ['study', 'python', 'is', 'happy']
stringlist.sort(key=len, reverse=True)
stringlist
['python', 'study', 'happy', 'is']
stringlist = ['study', 'python', 'is', 'happy']
stringlist.sort(key=len, reverse=False)
stringlist
['is', 'study', 'happy', 'python']

1.5 列表推导式

list1 = [i for i in range(0,10)]
list1 

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

list2 = [i for i in range(0,10) if i % 2 == 1]
list2 

[1, 3, 5, 7, 9]

foods = ["juce","milk","apple", "orange", "cherry ","banana ","grape"]
fruits = [fruit for fruit in foods[2:]]
fruits

['apple', 'orange', 'cherry ', 'banana ', 'grape']

# 阿凡提与国王比赛,放米问题

sum([2**i for i in range(64)]) 

18446744073709551615

原文地址:https://www.cnblogs.com/sinlearn/p/12665348.html