飞桨百度领航团零基础学Python之列表

列表

1 定义

列表list是一种组合数据类型,下面给出一些例子

list1 = [1, 2, 3, 4, 5 ]
list2 = ["a", "b", "c", "d","e","f"]
list3 = ['physics', 'chemistry', 1997, 2000]

2 方法

统计列表长度

len(list1)

列表索引和切片

list1 = ['a','b','c','d','e','f']
list1[2]	#列表的索引,输出'c'
list1[2:5]	#列表的切片,输出['c', 'd', 'e']

添加列表元素

list1 = ['a','b','c','d','e','f']
list1.append(5) #元素可以为数字、字符等
print(list1)	#输出['a','b','c','d','e','f', 5]
list1.append('g') # 在末尾添加元素
print(list1)	#输出['a','b','c','d','e','f', 5, 'g']
list1.insert(2, 'ooo')  # 在指定位置添加元素,如果指定的下标不存在,那么就是在末尾添加
print(list1)	#输出['a','b','ooo', 'c','d','e','f', 5,'g']
list2 = ['z','y','x']
list1.extend(list2) #合并两个list   list2中仍有元素
print(list1)	#输出['a','b','ooo', 'c','d','e','f', 5, 'g', 'z','y','x']
print(list2)	#输出['z','y','x']

删除列表元素

list1 = ['a','b','a','d','a','f']
list1.remove('a')	#删除列表中的的元素'a'
print(list1)		#输出['b', 'a', 'd', 'a', 'f']
list2 = ["a", "b", "c", "d","e","f"]
list2.pop()   #()中没有参数,删除列表尾部元素,输出'f'
print(list2)  #输出["a", "b", "c", "d","e"]
list2.pop(0)  #()中有索引,删除列表对应索引位置0的元素,输出'a'
print(list2)  #输出["b", "c", "d","e"]
list2.pop(1)  #()中有索引,删除列表对应索引位置1的元素,输出'c'
print(list2)  #输出["b", "d","e"]

count计数

list1 = ['a','b','a','d','a','f']
print(list1.count('a')) 	# 3

index查找

list1 = ['a','b','a','d','a','f']
print(list1.index('a')) 	# 0

判断列表中是否含有某元素

print('a' in list1)    		#True

3 列表生成式

#列表每一项+1
#普通方法
list_1 = [1,2,3,4,5]
for i in range(len(list_1)):
    list_1[i] += 1

list_1
#列表每一项+1
#列表生成式
list_1 = [1,2,3,4,5]
[n+1 for n in list_1]	#输出[2, 3, 4, 5, 6]
# 1-10之间所有数的平方 
[(n+1)**2 for n in range(10)]	#输出[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# 1-10之间所有数的平方 构成的字符串列表
[str((n+1)**2) for n in range(10)]	
#输出['1', '4', '9', '16', '25', '36', '49', '64', '81', '100']
# 列表中的每一个偶数项
#普通方法
list_1 = [1,2,3,4,5]
list_2 = []
for i in range(len(list_1)):
    if list_1[i] % 2 ==0:
        
        list_2.append(list_1[i])
list_2
#列表中的每一个偶数项
#列表生成式
list_1 = [1,2,3,4,5]
[n for n in list_1 if n%2==0]	#输出[2, 4]
# 字符串中所有以'sv'结尾的
list_2 = ['a','b','c_sv','d','e_sv']
[s for s in list_2 if s.endswith('sv')]	#输出['c_sv', 'e_sv']
# 取两个list的交集
list_A = [1,3,6,7,32,65,12]
list_B = [2,6,3,5,12]
[i for i in list_A if i in list_B]	#输出[3, 6, 12]

课程链接

飞桨百度领航团零基础学Python的课程链接如下:
https://aistudio.baidu.com/aistudio/course/introduce/7073
链接: link.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值