Python列表

时间:2020-02-23 14:42:57  来源:igfitidea点击:

今天我们将学习Python列表。

Python列表

List是Python中可用的通用数据类型。
基本上,python列表是用逗号分隔的值,称为项。
python中的列表写在方括号内。
有趣的是,列表中的项目不必是相同类型的。
例如;

#an empty list
empty_list=[]

#a list of strings
str_list=['this', 'is', 'a', 'list']

# a list of integers
int_list=[1,2,3,4,5]

#a list of mixed type of items
mixed_list=['this', 1, 'is', 2, 'a', 3, 'mixed',4, 'list',5]

# to print the lists
print(empty_list)
print(str_list)
print(int_list)
print(mixed_list)

在Python列表中访问项目

列表的每个项目都分配有一个数字-位置或者索引。
第一个索引为零,第二个索引为1,依此类推。

要访问列表中的项目,我们可以在方括号内使用这些索引号。
例如;

#a list of strings
str_list=['this', 'is', 'a', 'list']

#to access first item
print(str_list[0])
#to access second item
print(str_list[1])
#to access 4th element
print(str_list[3])

令人惊讶的事实是指数可能为负。
这意味着不要从列表的左侧读取,而应该从列表的右侧读取。

#a list of strings
str_list=['this', 'is', 'a', 'list']

#third item from left
print(str_list[2])

#third item from right
print(str_list[-3])

更新列表项目

我们可以简单地通过该项目的索引来更新列表中的一个或者多个项目。

#a list of strings
str_list=['this', 'is', 'a', 'list']

print("before updating the list: ")
print(str_list)
str_list[3]='updated list'
print("after updating the list: ")
print(str_list)

删除列表中的项目

要删除列表中的项目,有几种方法。
请看以下示例,以进一步研究它。

#an empty list
empty_list=[]

#a list of strings
str_list=['this', 'is', 'a', 'list']

#to remove a specific element, like 'is'
str_list.remove('is')
print(str_list)

#to remove an item of a specific index like 2
del str_list[2]
print(str_list)

#there are yet another way to remove an item of a specific index
str_list.pop(0)
print(str_list)

一些内置的python列表函数

有一些内置函数可以在python中操作列表。
让我们看下面的示例以进行理解。

#an empty list
empty_list=[]

#a list of strings
str_list=['this', 'is', 'a', 'list']

# add an element to the end of the list
str_list.append('appended')
print(str_list)

#insert an item at the defined index
str_list.insert(3,'inserted')
print(str_list)

#to get the index of the first matched item
print(str_list.index('a'))

#to count number of a specific element in a list
print(str_list.count('is'))

#to reverse the order of a list
str_list.reverse()
print(str_list)

#to sort the list in ascending order
str_list.sort()
print(str_list)