Python中常用的列表函数和字典函数及其用法
1. 列表函数
1.1 append(value):在列表的末尾添加一个元素。
例子:numbers = [1, 2, 3]
numbers.append(4)
print(numbers) # 输出:[1, 2, 3, 4]
1.2 insert(index, value):在列表的指定索引位置插入一个元素。
例子:numbers = [1, 2, 3]
numbers.insert(1, 4)
print(numbers) # 输出:[1, 4, 2, 3]
1.3 remove(value):从列表中删除指定的元素。
例子:numbers = [1, 2, 3]
numbers.remove(2)
print(numbers) # 输出:[1, 3]
1.4 pop(index):删除并返回列表中指定索引位置的元素。
例子:numbers = [1, 2, 3]
popped_number = numbers.pop(1)
print(popped_number) # 输出:2
print(numbers) # 输出:[1, 3]
1.5 index(value):返回列表中指定元素的第一个匹配项的索引。
例子:numbers = [1, 2, 3, 2]
print(numbers.index(2)) # 输出:1
1.6 count(value):返回列表中指定元素的出现次数。
例子:numbers = [1, 2, 3, 2]
print(numbers.count(2)) # 输出:2
2. 字典函数
2.1 keys():返回字典中所有的键。
例子:person = {"name": "John", "age": 30, "city": "New York"}
print(person.keys()) # 输出:dict_keys(['name', 'age', 'city'])
2.2 values():返回字典中所有的值。
例子:person = {"name": "John", "age": 30, "city": "New York"}
print(person.values()) # 输出:dict_values(['John', 30, 'New York'])
2.3 items():返回字典中所有的键值对。
例子:person = {"name": "John", "age": 30, "city": "New York"}
print(person.items()) # 输出:dict_items([('name', 'John'), ('age', 30), ('city', 'New York')])
2.4 get(key):返回字典中指定键的值。如果键不存在,可以指定默认值。
例子:person = {"name": "John", "age": 30}
print(person.get("name")) # 输出:John
print(person.get("city", "Unknown")) # 输出:Unknown
2.5 update(dictionary):将字典中的键值对更新到指定字典中。
例子:person = {"name": "John", "age": 30}
person.update({"city": "New York", "country": "USA"})
print(person) # 输出:{'name': 'John', 'age': 30, 'city': 'New York', 'country': 'USA'}
2.6 del dictionary[key]:删除字典中指定键的键值对。
例子:person = {"name": "John", "age": 30}
del person["age"]
print(person) # 输出:{'name': 'John'}
以上是Python中常用的列表函数和字典函数及其用法,它们可以帮助我们在处理数据时更加方便和高效地操作列表和字典。希望可以对你有所帮助!
