一阐肤、列表基本使用
1.列表遍歷
(1)for循環(huán)版本的遍歷
fruits = ['apple','banana','orange']
for fruit in fruits:
print(fruit)
#結(jié)果顯示
apple
banana
orange
(2)while循環(huán)版本的遍歷
index = 0
fruits = ['apple','banana','orange']
length = len(fruits)
while index < length:
fruit = fruits[index]
index += 1
print(fruit)
#結(jié)果顯示
apple
banana
orange
2.列表嵌套
test_list = [1,2,3,['a','b','c']]
for x in test_list:
if type(x) == list:
for y in x:
print(y)
else:
print(x)
#顯示結(jié)果
1
2
3
a
b
c
3.列表相加
a = [1,2,3]
b = [4,5,6]
c = a + b
print(c)
#顯示結(jié)果
[1, 2, 3, 4, 5, 6]
4.列表切片:跟字符串的切片操作一樣
a = [1,2,3,4,5,6,7,8,9]
temp1 = a[0:3]#取前三個值
temp2 = a[:]#取所有值
temp3 = a[0::2]#所有值以步進為2提取
temp4 = a[-3:]#取最后3個值
temp5 = a[-1:-4:-1]#取最后3個值得倒序
print(temp1)
print(temp2)
print(temp3)
print(temp4)
print(temp5)
#顯示結(jié)果
[1, 2, 3]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 3, 5, 7, 9]
[7, 8, 9]
[9, 8, 7]
#列表賦值
greet = ['hello','world']
greet[1] = 'feiniu002'
print(greet)
#顯示結(jié)果
['hello', 'feiniu002']
二拴测、列表常用方法
未完待續(xù)