Python中常用的数据结构包括列表(List)、元组(Tuple)、字典(Dictionary)、集合(Set)和字符串(String)。下面是一些基本的使用方法和操作:
列表(List)
创建列表:`my_list = [1, 2, 3, 4, 5]`
访问元素:`print(my_list)`
修改元素:`my_list = 10`
添加元素:`my_list.append(6)`
插入元素:`my_list.insert(0, 'new')`
删除元素:`my_list.pop(0)`
清空列表:`my_list.clear()`
删除指定元素:`my_list.remove(3)`
元组(Tuple)
创建元组:`my_tuple = (1, 2, 3)`
访问元素:`print(my_tuple)`
拆包赋值:`a, b, c = my_tuple`
字典(Dictionary)
创建字典:`my_dict = {'name': 'Alice', 'age': 30}`
访问元素:`print(my_dict['name'])`
修改元素:`my_dict['age'] = 31`
添加元素:`my_dict['city'] = 'New York'`
删除元素:`del my_dict['age']`
字典推导:`new_dict = {key: value for key, value in my_dict.items() if value > 30}`
集合(Set)
创建集合:`my_set = {1, 2, 3, 4, 5}`
添加元素:`my_set.add(6)`
删除元素:`my_set.remove(3)`
集合运算:`intersection = my_set.intersection(another_set)`
字符串(String)
创建字符串:`my_string = 'Hello, World!'`
访问字符:`print(my_string)`
修改字符:`my_string = my_string.replace('World', 'Python')`
字符串切片:`print(my_string[7:12])`
以上是Python中基本的数据结构及其操作方法。您可以根据需要选择合适的数据结构进行操作