標籤:range 構建 通過 pop 建立 code [] for remove
python中用 [ ] 來表示列表,列表中各元素以 , 分隔開,如
fruits = [‘apple‘, ‘orange‘, ‘banana‘, ‘pear‘, ‘watermelon‘]
print (fruits)
# result
[‘apple‘, ‘orange‘, ‘banana‘, ‘pear‘, ‘watermelon‘]
訪問列表中的元素:
1 # 列表中元素以0開始,若顯示orange,則:2 print (fruits[1])
# -1為列表的最後一個元素
print(fruits[-1])
# result
watermelon
修改列表中的元素
fruits[1] = peachprint (fruits)# result[‘apple‘, ‘peach‘, ‘banana‘, ‘pear‘, ‘watermelon‘]
列表末尾添加元素:
fruits.append(‘peach‘)print(fruits)# result[apple, banana, pear, watermelon, peach]
構建fruits列表
fruits = []fruits.append(‘apple‘)fruits.append(‘banana‘)fruits.append(‘pear‘)fruits.append(‘watermelon‘)print(fruits)# result[‘apple‘, ‘banana‘, ‘pear‘, ‘watermelon‘]
在列表中插入元素
fruits.insert(1, peach)print(fruits)# result[‘apple‘, ‘peach‘, ‘banana‘, ‘pear‘, ‘watermelon‘]
刪除列表中的元素
# deldel fruits[1]print (fruits)# result[‘apple‘, ‘pear‘, ‘watermelon‘]# pop()apple = fruits.pop(0)print (apple)print (fruits)# resultapple[‘banana‘, ‘pear‘, ‘‘watermelon‘]# remove()fruits.remove(‘pear‘)print(fruits)# result[‘apple‘, ‘banana‘, ‘watermelon‘]
列表排序
# 永久排序fruits.sort()print (fruits)# result[‘apple‘, ‘banana‘, ‘pear‘, ‘watermelon‘]# 倒序fruits.sort(reverse=True)print(fruits)[‘watermelon‘, ‘pear‘, ‘banana‘, ‘apple‘]# 臨時排序print(fruits)print(sorted(fruits))print(fruits)# result 假設原fruits為[ ‘banana‘, ‘apple‘, ‘pear‘, ‘watermelon‘][ ‘banana‘, ‘apple‘, ‘pear‘, ‘watermelon‘][‘apple‘, ‘banana‘, ‘pear‘, ‘watermelon‘][ ‘banana‘, ‘apple‘, ‘pear‘, ‘watermelon‘]
列表倒序
fruits.reverse()print(fruits)# result[‘watermelon‘, ‘pear‘, ‘banana‘, ‘apple‘]
擷取列表長度
print(len(fruits))# result4
列表遍曆:
for fruit in fruits: print(fruit)# resultapplebananapeerwatermelon
函數range
for value in range(1, 5): print (value)# result 不包含末尾值1234# 使用range建立數字列表values = list(range(1, 6))print (values)# result[1, 2, 3, 4, 5]# 列印偶數values = list(range(2, 11, 2))print (values)# result[2, 4, 6, 8, 10]# 數字統計計算values = [1, 2, 3, 4, 5, 6, 7, 8, 9]print(min(values))print(max(values))print(sum(value))
列表切片
print(fruits[0:3])# result 左閉右開 [‘apple‘, ‘banana‘, ‘pear‘]
print(fruits[:3])
# result 左側無起始值,則預設從開頭位置取,若右側無終止值,則一直取到list的末尾
[‘apple‘, ‘banana‘, ‘pear‘]
切片遍曆
for fruit in fruits[0:3] print (fruit)# result[‘apple‘, ‘banana‘, ‘pear‘]
通過切片複製列表
my_fruits = fruits[:]print (my_fruits)# result[‘apple‘, ‘banana‘, ‘pear‘, ‘watermelon‘]
python列表操作