📅  最后修改于: 2020-10-24 09:05:18             🧑  作者: Mango
Python的列表用于存储各种类型的数据的序列。 Python列表是可变类型,这意味着我们可以在创建后修改其元素。但是, Python由六种能够存储序列的数据类型组成,但是最常见和最可靠的类型是列表。
列表可以定义为不同类型的值或项目的集合。列表中的项目用逗号(,)分隔,并用方括号[]括起来。
列表可以定义如下
L1 = ["John", 102, "USA"]
L2 = [1, 2, 3, 4, 5, 6]
如果我们尝试使用type()函数printL1,L2和L3的类型,那么它将显示为列表。
print(type(L1))
print(type(L2))
输出:
该列表具有以下特征:
让我们检查列表是有序的第一条语句。
a = [1,2,"Peter",4.50,"Ricky",5,6]
b = [1,2,5,"Peter",4.50,"Ricky",6]
a ==b
输出:
False
两个列表都由相同的元素组成,但是第二个列表更改了第5个元素的索引位置,这违反了列表的顺序。比较两个列表时,它返回false。
列表在生命周期内维持元素的顺序。这就是为什么它是对象的有序集合。
a = [1, 2,"Peter", 4.50,"Ricky",5, 6]
b = [1, 2,"Peter", 4.50,"Ricky",5, 6]
a == b
输出:
True
让我们详细看一下清单示例。
emp = ["John", 102, "USA"]
Dep1 = ["CS",10]
Dep2 = ["IT",11]
HOD_CS = [10,"Mr. Holding"]
HOD_IT = [11, "Mr. Bewon"]
print("printing employee data...")
print("Name : %s, ID: %d, Country: %s"%(emp[0],emp[1],emp[2]))
print("printing departments...")
print("Department 1:\nName: %s, ID: %d\nDepartment 2:\nName: %s, ID: %s"%(Dep1[0],Dep2[1],Dep2[0],Dep2[1]))
print("HOD Details ....")
print("CS HOD Name: %s, Id: %d"%(HOD_CS[1],HOD_CS[0]))
print("IT HOD Name: %s, Id: %d"%(HOD_IT[1],HOD_IT[0]))
print(type(emp),type(Dep1),type(Dep2),type(HOD_CS),type(HOD_IT))
输出:
printing employee data...
Name : John, ID: 102, Country: USA
printing departments...
Department 1:
Name: CS, ID: 11
Department 2:
Name: IT, ID: 11
HOD Details ....
CS HOD Name: Mr. Holding, Id: 10
IT HOD Name: Mr. Bewon, Id: 11
在上面的示例中,我们创建了包含员工和部门详细信息的列表,并打印了相应的详细信息。观察上面的代码,以更好地了解列表的概念。
索引的处理方式与字符串处理方式相同。可以使用slice运算符[]访问列表中的元素。
索引从0开始,到长度-1。列表的第一个元素存储在第0个索引,列表的第二个元素存储在第一个索引,依此类推。
我们可以使用以下语法获取列表的子列表。
list_varible(start:stop:step)
考虑以下示例:
list = [1,2,3,4,5,6,7]
print(list[0])
print(list[1])
print(list[2])
print(list[3])
# Slicing the elements
print(list[0:6])
# By default the index value is 0 so its starts from the 0th element and go for index -1.
print(list[:])
print(list[2:5])
print(list[1:6:2])
输出:
1
2
3
4
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
[2, 4, 6]
与其他语言不同, Python还提供了使用负索引的灵活性。负索引从右开始计数。列表的最后一个元素(最右边)的索引为-1;其相邻的左侧元素位于索引-2处,依此类推,直到遇到最左侧的元素。
让我们看下面的示例,在该示例中,我们将使用负索引来访问列表的元素。
list = [1,2,3,4,5]
print(list[-1])
print(list[-3:])
print(list[:-1])
print(list[-3:-1])
输出:
5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]
如上所述,我们可以使用负索引来获取元素。在上面的代码中,第一个print语句返回了列表的最右边的元素。第二个print语句返回子列表,依此类推。
列表是Python用途最广泛的数据结构,因为它们是可变的,并且可以使用slice和Assignment运算符更新其值。
Python还提供了append()和insert()方法,可用于将值添加到列表中。
考虑下面的示例来更新列表中的值。
list = [1, 2, 3, 4, 5, 6]
print(list)
# It will assign value to the value to the second index
list[2] = 10
print(list)
# Adding multiple-element
list[1:3] = [89, 78]
print(list)
# It will add value at the end of the list
list[-1] = 25
print(list)
输出:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
也可以使用del关键字删除列表元素。如果我们不知道要从列表中删除哪个元素, Python还将为我们提供remove()方法。
考虑下面的示例以删除列表元素。
list = [1, 2, 3, 4, 5, 6]
print(list)
# It will assign value to the value to second index
list[2] = 10
print(list)
# Adding multiple element
list[1:3] = [89, 78]
print(list)
# It will add value at the end of the list
list[-1] = 25
print(list)
输出:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
串联(+)和重复(*)运算符的工作方式与处理字符串的方式相同。
让我们看看列表如何响应各种运算符。
Consider a Lists l1 = [1, 2, 3, 4], and l2 = [5, 6, 7, 8] to perform operation.
Operator | Description | Example |
---|---|---|
Repetition | The repetition operator enables the list elements to be repeated multiple times. |
L1*2 = [1, 2, 3, 4, 1, 2, 3, 4] |
Concatenation | It concatenates the list mentioned on either side of the operator. |
l1+l2 = [1, 2, 3, 4, 5, 6, 7, 8] |
Membership | It returns true if a particular item exists in a particular list otherwise false. |
print(2 in l1) prints True. |
Iteration | The for loop is used to iterate over the list elements. |
for i in l1: print(i) Output 1 2 3 4 |
Length | It is used to get the length of the list |
len(l1) = 4 |
可以使用for-in循环来迭代列表。一个包含四个字符串的简单列表,可以按如下方式进行迭代。
list = ["John", "David", "James", "Jonathan"]
for i in list:
# The i variable will iterate over the elements of the List and contains each element in each iteration.
print(i)
输出:
John
David
James
Jonathan
Python提供了append()函数,该函数用于将元素添加到列表中。但是,append()函数只能将值添加到列表的末尾。
考虑以下示例,在该示例中,我们从用户那里获取列表的元素,并将该列表打印在控制台上。
#Declaring the empty list
l =[]
#Number of elements will be entered by the user
n = int(input("Enter the number of elements in the list:"))
# for loop to take the input
for i in range(0,n):
# The input is taken from the user and added to the list as the item
l.append(input("Enter the item:"))
print("printing the list items..")
# traversal loop to print the list items
for i in l:
print(i, end = " ")
输出:
Enter the number of elements in the list:5
Enter the item:25
Enter the item:46
Enter the item:12
Enter the item:75
Enter the item:42
printing the list items
25 46 12 75 42
Python提供了remove()函数,该函数用于从列表中删除元素。考虑以下示例以了解此概念。
范例-
list = [0,1,2,3,4]
print("printing original list: ");
for i in list:
print(i,end=" ")
list.remove(2)
print("\nprinting the list after the removal of first element...")
for i in list:
print(i,end=" ")
输出:
printing original list:
0 1 2 3 4
printing the list after the removal of first element...
0 1 3 4
Python提供了以下内置函数,可与列表一起使用。
SN | Function | Description | Example |
---|---|---|---|
1 | cmp(list1, list2) | It compares the elements of both the lists. | This method is not used in the Python 3 and the above versions. |
2 | len(list) | It is used to calculate the length of the list. |
L1 = [1,2,3,4,5,6,7,8] print(len(L1)) 8 |
3 | max(list) | It returns the maximum element of the list. |
L1 = [12,34,26,48,72] print(max(L1)) 72 |
4 | min(list) | It returns the minimum element of the list. |
L1 = [12,34,26,48,72] print(min(L1)) 12 |
5 | list(seq) | It converts any sequence to the list. |
str = "Johnson" s = list(str) print(type(s)) |
让我们看几个列表示例。
示例:1-编写程序以删除列表中的重复元素。
list1 = [1,2,2,3,55,98,65,65,13,29]
# Declare an empty list that will store unique values
list2 = []
for i in list1:
if i not in list2:
list2.append(i)
print(list2)
输出:
[1, 2, 3, 55, 98, 65, 13, 29]
示例:2-编写程序以查找列表中元素的总和。
list1 = [3,4,5,9,10,12,24]
sum = 0
for i in list1:
sum = sum+i
print("The sum is:",sum)
输出:
The sum is: 67
示例:3-编写程序以查找包含至少一个公共元素的列表。
list1 = [1,2,3,4,5,6]
list2 = [7,8,9,2,10]
for x in list1:
for y in list2:
if x == y:
print("The common element is:",x)
输出:
The common element is: 2