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_cities print(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