小热身
写一个1到99的列表
示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 写一个1到99的列表
# While循环
list = []
i = 0
while i < 100:
i = i + 1
list.append(i)
print(list)
运行结果
D:\PythonProject>python Run.py
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
List的切片
必须承认这个神奇了,第一次遇到这样的写法
取指定index范围内的数据[fist, last)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 切片:取指定index范围内的数据[fist, last)
mList = ["小猫", "dog", "美玲", "川外"]
print(mList[1:3])
运行结果
D:\PythonProject>python Run.py
['dog', '美玲']
取倒数第x个
实例代码
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 切片:取指定index范围内的数据[fist, last)
mList = ["小猫", "dog", "美玲", "川外"]
print(mList[-1])
运行结果
D:\PythonProject>python Run.py
川外
实战
建立一个0~99的列表
示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 切片实战
# 创建一个0-99的数列
mList = list(range(100))
print(mList)
运行结果
D:\PythonProject>python Run.py
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
取前10的数据
示例
# 取前10个数据
print("取前10数据",mList[:10])
运行结果
取前10数据 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
取倒数10个的数据
示例代码
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 切片实战
# 创建一个0-99的数列
mList = list(range(100))
# 取倒数10个数据
print("取倒数10数据",mList[-10:])
运行结果
D:\PythonProject>python Run.py
取倒数10数据 [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
前11-20个数
示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 切片实战
# 创建一个0-99的数列
mList = list(range(100))
# 前11-20个数
print("取前11-20个数",mList[10:20])
运行结果
D:\PythonProject>python Run.py
取前11-20个数 [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
前10个数,每两个取一个
示例代码
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 切片实战
# 创建一个0-99的数列
mList = list(range(100))
# 前10个数,每两个取一个
print("前10个数,每两个取一个",mList[:10:2])
运行结果
D:\PythonProject>python Run.py
前10个数,每两个取一个 [0, 2, 4, 6, 8]
所有数,每5个取一个
示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 切片实战
# 创建一个0-99的数列
mList = list(range(100))
# 所有数,每5个取一个
print("所有数,每5个取一个",mList[::5])
运行结果
D:\PythonProject>python Run.py
所有数,每5个取一个 [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
Turple的切片
示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Turple的切片
print("Turple的切片",(1,2,3,4,5)[1:3])
运行结果
D:\PythonProject>python Run.py
Turple的切片 (2, 3)
字符串的切片
示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 字符串的切片
print("字符串的切片"[0:3])
运行结果
D:\PythonProject>python Run.py
字符串