Python3 列表(List)基礎
阿新 • • 發佈:2018-09-20
使用 上海 出現 3.3 san fff class ror 追加
1、初始化
cities = ["北京","上海",["深圳","廣州"],"杭州"] jobs = [] jobs.append("人工智能") jobs.append("後端開發") jobs.append("前端開發") jobs.append("數據分析") print(cities) print(jobs)
打印輸出結果:
[‘北京‘, ‘上海‘, [‘深圳‘, ‘廣州‘], ‘杭州‘] [‘人工智能‘, ‘後端開發‘, ‘前端開發‘, ‘數據分析‘]
2、切片
print(cities[0:-1:2])
打印輸出結果:
[‘北京‘, [‘深圳‘, ‘廣州‘]]
print(cities[::2])
打印輸出結果:
[‘北京‘, [‘深圳‘, ‘廣州‘]]
print(cities[:])
打印輸出結果:
[‘北京‘, ‘上海‘, [‘深圳‘, ‘廣州‘], ‘杭州‘]
3、方法
3.1、insert()
向列表中插入數據。
cities = ["北京","上海",["深圳","廣州"],"杭州"] cities.insert(1,"天津") print(cities)
打印輸出結果:
[‘北京‘, ‘天津‘, ‘上海‘, [‘深圳‘, ‘廣州‘], ‘杭州‘]
3.2、remove()
將一條數據從列表中移除。
cities = ["北京","上海",["深圳","廣州"],"杭州"] cities.remove("上海") print(cities)
打印輸出結果:
[‘北京‘, [‘深圳‘, ‘廣州‘], ‘杭州‘]
3.3、del
3.3.1、刪除列表中的元素
cities = ["北京","上海",["深圳","廣州"],"杭州"] del cities[1] print(cities)
打印輸出結果:
[‘北京‘, [‘深圳‘, ‘廣州‘], ‘杭州‘]
3.3.2、刪除列表
new_cities = ["武漢","成都","重慶","南京"] del new_citiesprint(new_cities)
打印輸出結果:
NameError: name ‘new_cities‘ is not defined
3.4、pop()
用於移除列表中的一個元素(默認最後一個元素),並且返回該元素的值。
cities = ["北京","上海",["深圳","廣州"],"杭州"] cities.pop(1) print(cities)
打印輸出結果:
[‘北京‘, [‘深圳‘, ‘廣州‘], ‘杭州‘]
3.5、index()
用於從列表中找出某個值第一個匹配項的索引位置。
cities = ["北京","上海",["深圳","廣州"],"杭州"] print(cities.index("杭州"))
打印輸出結果:3
3.6、count()
用於統計字符串裏某個字符出現的次數。
cities = ["北京","上海",["深圳","廣州"],"杭州"] cities.append("北京") cities.append("北京") print(cities)
打印輸出結果:3
3.7、reverse()
用於反向列表中元素。
cities = ["北京","上海",["深圳","廣州"],"杭州"] cities.reverse() print(cities)
打印輸出結果:
[‘杭州‘, [‘深圳‘, ‘廣州‘], ‘上海‘, ‘北京‘]
3.8、sort()
用於對原列表進行排序,如果指定參數,則使用比較函數指定的比較函數。
list_r = ["A","B","C","x","a"]
# 降序
list_r.sort(reverse=True)
print(list_r)
# 升序
list_r.sort(reverse=False)
print(list_r)
打印輸出結果:
[‘x‘, ‘a‘, ‘C‘, ‘B‘, ‘A‘] [‘A‘, ‘B‘, ‘C‘, ‘a‘, ‘x‘]
3.9、extend()
用於在列表末尾一次性追加另一個序列中的多個值(用新列表擴展原來的列表)。
cities = ["北京","上海",["深圳","廣州"],"杭州"] new_cities = ["武漢","成都","重慶","南京"] cities.extend(new_cities) print(cities)
輸出打印結果:
[‘北京‘, ‘北京‘, ‘北京‘, ‘杭州‘, ‘武漢‘, ‘成都‘, ‘重慶‘, ‘南京‘, ‘武漢‘, ‘成都‘, ‘重慶‘, ‘南京‘]
3.10、len()
計算列表元素個數。
cities = ["北京","上海",["深圳","廣州"],"杭州"] print(cities) nums = len(cities) print(nums)
打印輸出結果:
[‘北京‘, ‘上海‘, [‘深圳‘, ‘廣州‘], ‘杭州‘] 4
Python3 列表(List)基礎