列表
1.列表的创建
lis = [1, 2, 3]
print(lis, type(lis))
[1, 2, 3] <class 'list'>
2.通过索引(index)来获取列表中的元素
nums1 = [10, 20, 30, 40, 50]
print(nums1[1])
20
print(nums1[-2])
40
print(len(nums1))
5
3.切片
lis = ['钢铁侠', '雷神', '绿巨人', '美队', '蚁人', '蜘蛛侠', '黑寡妇']
print('开始',lis[:3])
开始 ['钢铁侠', '雷神', '绿巨人']
print('结束',lis[3:])
结束 ['美队', '蚁人', '蜘蛛侠', '黑寡妇']
print('两边',lis[:])
两边 ['钢铁侠', '雷神', '绿巨人', '美队', '蚁人', '蜘蛛侠', '黑寡妇']
print('步长',lis[::2])
步长 ['钢铁侠', '绿巨人', '蚁人', '黑寡妇']
4.通用操作
list_one = [1, 2, 3]
list_tow = [7, 8, 9]
totle = list_one + list_tow
print(totle)
[1, 2, 3, 7, 8, 9]
list_demo = [1, 2, 3] * 3
print(list_demo)
[1, 2, 3, 1, 2, 3, 1, 2, 3]
hero = ['钢铁侠', '雷神', '绿巨人', '美队', '蚁人', '蜘蛛侠', '黑寡妇']
print('钢铁侠' in hero)
True
print('钢铁侠' not in hero)
False
demo = [1, 2, 3, 7, 8, 9]
print(min(demo))
1
print(max(demo))
9
hero = ['钢铁侠', '雷神', '绿巨人', '美队', '蚁人', '蜘蛛侠', '黑寡妇']
print(hero.index('雷神'))
1
5.修改列表
hero = ['钢铁侠', '雷神', '绿巨人', '美队', '蚁人', '蜘蛛侠', '黑寡妇']
hero[3] = '中华小当家'
print(hero)
['钢铁侠', '雷神', '绿巨人', '中华小当家', '蚁人', '蜘蛛侠', '黑寡妇']
hero_del = ['钢铁侠', '雷神', '绿巨人', '美队', '蚁人', '蜘蛛侠', '黑寡妇']
del hero_del[2]
print(hero_del)
['钢铁侠', '雷神', '美队', '蚁人', '蜘蛛侠', '黑寡妇']
hero_qiepian = ['钢铁侠', '雷神', '绿巨人', '美队', '蚁人', '蜘蛛侠', '黑寡妇']
hero_qiepian[2] = '小伙子'
print(hero_qiepian)
['钢铁侠', '雷神', '小伙子', '美队', '蚁人', '蜘蛛侠', '黑寡妇']
hero_qiepian[0:3] = ['1', '2', '3']
print(hero_qiepian)
['1', '2', '3', '美队', '蚁人', '蜘蛛侠', '黑寡妇']
6.列表的方法
one = ['1', '2', '3', '美队', '蚁人', '蜘蛛侠', '黑寡妇']
one.append('炸弹人')
print(one)
['1', '2', '3', '美队', '蚁人', '蜘蛛侠', '黑寡妇', '炸弹人']
two = ['1', '2', '3', '美队', '蚁人', '蜘蛛侠', '黑寡妇']
two.insert(2, '100')
print(two)
['1', '2', '100', '3', '美队', '蚁人', '蜘蛛侠', '黑寡妇']
three = ['美队', '蚁人', '蜘蛛侠', '黑寡妇']
three.extend(['123', '234'])
print(three)
['美队', '蚁人', '蜘蛛侠', '黑寡妇', '123', '234']
three = ['美队', '蚁人', '蜘蛛侠', '黑寡妇']
three += ['789']
print(three)
['美队', '蚁人', '蜘蛛侠', '黑寡妇', '789']
four = ['钢铁侠', '雷神', '绿巨人', '美队']
result = four.pop(2)
print(result)
绿巨人
five = [1, 2, 7, 4, 5, 6]
five.reverse()
print(five)
[6, 5, 4, 7, 2, 1]
six = [1, 2, 7, 4, 5, 6]
six.sort()
print(six)
[1, 2, 4, 5, 6, 7]
seven = [1, 2, 7, 4, 5, 6]
seven.sort(reverse=True)
print(seven)
[7, 6, 5, 4, 2, 1]
7.遍历列表
first = ['美队', '蚁人', '蜘蛛侠']
i = 0
while i < len(first):
print(first[i])
i += 1
美队
蚁人
蜘蛛侠
first = ['美队', '蚁人', '蜘蛛侠']
for i in first:
print(i)
美队
蚁人
蜘蛛侠
8.range()函数
first = ['美队', '蚁人', '蜘蛛侠']
for i in first:
print(i)
print(type(i))
美队
<class 'str'>
蚁人
<class 'str'>
蜘蛛侠
<class 'str'>
for i in range(5):
print(type(i))
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>