Python如何设置list

原创
admin 2小时前 阅读数 7 #Python

Python中List的设置与操作

Python中的List是一种可变的数据结构,它可以包含各种类型的元素,如数字、字符串、列表等,以下是Python中如何设置List的一些基本操作:

1、创建List

可以使用方括号[]创建List,也可以在List中嵌套其他List。

list1 = [1, 2, 3]
list2 = [‘a’, ‘b’, ‘c’]
list3 = [[1, 2], [3, 4], [5, 6]]

2、添加元素

使用append()方法在List末尾添加元素,使用insert()方法在指定位置插入元素。

list1 = [1, 2, 3]
list1.append(4)  # list1 now is [1, 2, 3, 4]
list1.insert(1, ‘a’)  # list1 now is [1, ‘a’, 2, 3, 4]

3、删除元素

使用remove()方法删除指定元素,使用pop()方法删除并返回指定位置的元素。

list1 = [1, 2, 3]
list1.remove(2)  # list1 now is [1, 3]
list1.pop(0)  # list1 now is [3], and the returned value is 1

4、修改元素

通过索引直接修改List中的元素。

list1 = [1, 2, 3]
list1[1] = 4  # list1 now is [1, 4, 3]

5、查找元素

使用index()方法查找指定元素在List中的位置,如果元素不存在,则会抛出ValueError。

list1 = [1, 2, 3]
print(list1.index(2))  # output is 1
热门