Python列表

一、列表基本使用

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ù)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容