Python 列表


Python 列表就像动态大小的数组,用其他语言声明(C++ 中的向量和 Java 中的 ArrayList)。用简单的语言来说,列表就是事物的集合,用 [ ] 括起来并用逗号分隔。

列表是一种序列数据类型,用于存储数据集合。元组和字符串是其他类型的序列数据类型。

Python 中的列表示例

这里我们使用 [] 创建 Python列表

Var = ["Geeks", "for", "Geeks"]
print(Var)

输出:

["Geeks", "for", "Geeks"]

列表是最简单的容器,是 Python 语言不可或缺的一部分。列表不必总是同质的,这使它成为Python中最强大的工具。单个列表可能包含数据类型,如整数、字符串和对象。列表是可变的,因此即使在创建之后也可以更改。

在 Python 中创建列表

Python 中的列表可以通过将序列放在方括号 [] 内来创建。与Sets不同,列表不需要内置函数来创建列表。

注意:与集合不同,列表可能包含可变元素。

示例 1:在 Python 中创建列表

# Python program to demonstrate
# Creation of List

# Creating a List
List = []
print("Blank List: ")
print(List)

# Creating a List of numbers
List = [10, 20, 14]
print("\nList of numbers: ")
print(List)

# Creating a List of strings and accessing
# using index
List = ["Geeks", "For", "Geeks"]
print("\nList Items: ")
print(List[0])
print(List[2])

输出

Blank List: 
[]

List of numbers: 
[10, 20, 14]

List Items: 
Geeks
Geeks

创建列表的复杂性

时间复杂度: O(1)

空间复杂度: O(n)

示例 2:创建包含多个不同或重复元素的列表

列表可能包含具有不同位置的重复值,因此,多个不同或重复的值可以在创建列表时作为序列传递。

# Creating a List with
# the use of Numbers
# (Having duplicate values)
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print("\nList with the use of Numbers: ")
print(List)

# Creating a List with
# mixed type of values
# (Having numbers and strings)
List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']
print("\nList with the use of Mixed Values: ")
print(List)

输出

使用数字列表:
[1, 2, 4, 4, 3, 3, 3, 6, 5]

使用混合值列表:
[1, 2, 'Geeks', 4, 'For', 6 , '极客']

访问列表中的元素

要访问列表项,请参考索引号。使用索引运算符 [ ] 访问列表中的项目。索引必须是整数。使用嵌套索引访问嵌套列表。

示例 1:访问列表中的元素

# Python program to demonstrate
# accessing of element from list

# Creating a List with
# the use of multiple values
List = ["Geeks", "For", "Geeks"]

# accessing a element from the
# list using index number
print("Accessing a element from the list")
print(List[0])
print(List[2])

输出

Accessing a element from the list
Geeks
Geeks

示例 2:访问多维列表中的元素

# Creating a Multi-Dimensional List
# (By Nesting a list inside a List)
List = [['Geeks', 'For'], ['Geeks']]

# accessing an element from the
# Multi-Dimensional List using
# index number
print("Accessing a element from a Multi-Dimensional list")
print(List[0][1])
print(List[1][0])

输出

Accessing a element from a Multi-Dimensional list
For
Geeks

负索引

在 Python 中,负序索引表示从数组末尾开始的位置。不必像 List[len(List)-3] 那样计算偏移量,只写 List[-3] 就足够了。负索引表示从末尾开始,-1 表示最后一项,-2 表示倒数第二项,依此类推。

List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']

# accessing an element using
# negative indexing
print("Accessing element using negative indexing")

# print the last element of list
print(List[-1])

# print the third last element of list
print(List[-3])

输出

Accessing element using negative indexing
Geeks
For

访问列表中元素的复杂性:

时间复杂度: O(1)

空间复杂度: O(1)

获取 Python 列表的大小

Python len()用于获取列表的长度。

# Creating a List
List1 = []
print(len(List1))

# Creating a List of numbers
List2 = [10, 20, 14]
print(len(List2))

输出

0 
3

获取 Python 列表的输入

我们可以将元素列表的输入作为字符串、整数、浮点数等。但默认的是字符串。

示例 1:

# Python program to take space
# separated input as a string
# split and store it to a list
# and print the string list

# input the list as string
string = input("Enter elements (Space-Separated): ")

# split the strings and store it to a list
lst = string.split()  
print('The list is:', lst)   # printing the list

输出:

Enter elements: GEEKS FOR GEEKS
The list is: ['GEEKS', 'FOR', 'GEEKS']

示例 2:

# input size of the list
n = int(input("Enter the size of list : "))
# store integers in a list using map,
# split and strip functions
lst = list(map(int, input("Enter the integer\
elements:").strip().split()))[:n]

# printing the list
print('The list is:', lst)

输出:

Enter the size of list : 4
Enter the integer elements: 6 3 9 10
The list is: [6, 3, 9, 10]

将元素添加到 Python 列表

方法一:使用append()方法

可以使用内置的append()函数将元素添加到列表中。使用 append() 方法一次只能将一个元素添加到列表中,对于使用 append() 方法添加多个元素,使用循环。也可以使用 append 方法将元组添加到列表中,因为元组是不可变的。与集合不同,列表也可以使用 append() 方法添加到现有列表中。

# Python program to demonstrate
# Addition of elements in a List

# Creating a List
List = []
print("Initial blank List: ")
print(List)

# Addition of Elements
# in the List
List.append(1)
List.append(2)
List.append(4)
print("\nList after Addition of Three elements: ")
print(List)

# Adding elements to the List
# using Iterator
for i in range(1, 4):
    List.append(i)
print("\nList after Addition of elements from 1-3: ")
print(List)

# Adding Tuples to the List
List.append((5, 6))
print("\nList after Addition of a Tuple: ")
print(List)

# Addition of List to a List
List2 = ['For', 'Geeks']
List.append(List2)
print("\nList after Addition of a List: ")
print(List)

输出

Initial blank List: 
[]

List after Addition of Three elements: 
[1, 2, 4]

List after Addition of elements from 1-3: 
[1, 2, 4, 1, 2, 3]

List after Addition of a Tuple: 
[1, 2, 4, 1, 2, 3, (5, 6)]

List after Addition of a List: 
[1, 2, 4, 1, 2, 3, (5, 6), ['For', 'Geeks']]

在列表中添加元素的复杂性(append()方法):

时间复杂度: O(1)

空间复杂度: O(1)

方法二:使用insert()方法

append() 方法仅适用于在 List 末尾添加元素,要在所需位置添加元素,使用insert()方法。与仅接受一个参数的 append() 不同,insert() 方法需要两个参数(位置、值)。

# Python program to demonstrate 
# Addition of elements in a List

# Creating a List
List = [1,2,3,4]
print("Initial List: ")
print(List)

# Addition of Element at 
# specific Position
# (using Insert Method)
List.insert(3, 12)
List.insert(0, 'Geeks')
print("\nList after performing Insert Operation: ")
print(List)

输出

Initial List: 
[1, 2, 3, 4]

List after performing Insert Operation: 
['Geeks', 1, 2, 3, 12, 4]

在列表中添加元素的复杂性(insert() 方法):

时间复杂度: O(n)

空间复杂度: O(1)

方法 3:使用 extend() 方法

除了 append() 和 insert() 方法之外,还有一种添加元素的方法,extend(),该方法用于在列表末尾同时添加多个元素。

注意:append() 和 extend()方法只能在末尾添加元素。

# Python program to demonstrate
# Addition of elements in a List

# Creating a List
List = [1, 2, 3, 4]
print("Initial List: ")
print(List)

# Addition of multiple elements
# to the List at the end
# (using Extend Method)
List.extend([8, 'Geeks', 'Always'])
print("\nList after performing Extend Operation: ")
print(List)

输出

Initial List: 
[1, 2, 3, 4]

List after performing Extend Operation: 
[1, 2, 3, 4, 8, 'Geeks', 'Always']

在列表中添加元素的复杂性(扩展()方法):

时间复杂度: O(n)

空间复杂度: O(1)

反转列表

可以使用Python 中的 reverse() 方法反转列表。

# Reversing a list
mylist = [1, 2, 3, 4, 5, 'Geek', 'Python']
mylist.reverse()
print(mylist)

输出

['Python', 'Geek', 5, 4, 3, 2, 1]

从列表中删除元素

方法一:使用remove()方法

可以使用内置的remove()函数从列表中删除元素,但如果列表中不存在该元素,则会出现错误。Remove() 方法一次只删除一个元素,要删除一系列元素,使用迭代器。remove() 方法删除指定的项目。

注意: List 中的 Remove 方法只会删除第一次出现的搜索元素。

示例 1:

# Python program to demonstrate
# Removal of elements in a List

# Creating a List
List = [1, 2, 3, 4, 5, 6,
        7, 8, 9, 10, 11, 12]
print("Initial List: ")
print(List)

# Removing elements from List
# using Remove() method
List.remove(5)
List.remove(6)
print("\nList after Removal of two elements: ")
print(List)

输出

Initial List: 
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

List after Removal of two elements: 
[1, 2, 3, 4, 7, 8, 9, 10, 11, 12]

示例 2:

# Creating a List
List = [1, 2, 3, 4, 5, 6,
        7, 8, 9, 10, 11, 12]
# Removing elements from List
# using iterator method
for i in range(1, 5):
    List.remove(i)
print("\nList after Removing a range of elements: ")
print(List)

输出

List after Removing a range of elements: 
[5, 6, 7, 8, 9, 10, 11, 12]

删除列表中元素的复杂性(remove() 方法):

时间复杂度: O(n)

空间复杂度: O(1)

方法二:使用pop()方法

pop() 函数也可用于从列表中移除和返回一个元素,但默认情况下它只移除列表的最后一个元素,从列表的特定位置移除元素,传递元素的索引作为 pop() 方法的参数。

List = [1, 2, 3, 4, 5]

# Removing element from the
# Set using the pop() method
List.pop()
print("\nList after popping an element: ")
print(List)

# Removing element at a
# specific location from the
# Set using the pop() method
List.pop(2)
print("\nList after popping a specific element: ")
print(List)

输出

List after popping an element: 
[1, 2, 3, 4]

List after popping a specific element: 
[1, 2, 4]

删除列表中元素的复杂性(pop() 方法):

时间复杂度: O(1)/O(n)(O(1) 删除最后一个元素,O(n) 删除第一个和中间元素)

空间复杂度: O(1)

列表的切片

我们可以使用切片获取子字符串和子列表。在 Python List 中,有多种方法可以打印包含所有元素的整个列表,但是要打印列表中特定范围的元素,我们使用 Slice操作。

使用冒号(:)对列表执行切片操作。

要打印从开始到范围的元素,请使用:

[: Index]

从最终用途打印元素:

[: Index]

打印特定索引中的元素直到最终使用

[:-Index]

要以相反的顺序打印整个列表,请使用

[::-1]

注意 –要从后端打印 List 的元素,请使用负索引。

蟒蛇列表切片

理解列表的切片:

  • pr[0] accesses the first item, 2.
  • pr[-4] accesses the fourth item from the end, 5.
  • pr[2:] accesses [5, 7, 11, 13], a list of items from third to last.
  • pr[:4] accesses [2, 3, 5, 7], a list of items from first to fourth.
  • pr[2:4] accesses [5, 7], a list of items from third to fifth.
  • pr[1::2] accesses [3, 7, 13], alternate items, starting from the second item.
# Python program to demonstrate
# Removal of elements in a List

# Creating a List
List = ['G', 'E', 'E', 'K', 'S', 'F',
        'O', 'R', 'G', 'E', 'E', 'K', 'S']
print("Initial List: ")
print(List)

# Print elements of a range
# using Slice operation
Sliced_List = List[3:8]
print("\nSlicing elements in a range 3-8: ")
print(Sliced_List)

# Print elements from a
# pre-defined point to end
Sliced_List = List[5:]
print("\nElements sliced from 5th "
      "element till the end: ")
print(Sliced_List)

# Printing elements from
# beginning till end
Sliced_List = List[:]
print("\nPrinting all elements using slice operation: ")
print(Sliced_List)

输出

Initial List: 
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']

Slicing elements in a range 3-8: 
['K', 'S', 'F', 'O', 'R']

Elements sliced from 5th element till the end: 
['F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']

Printing all elements using slice operation: 
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']

负索引列表切片

# Creating a List
List = ['G', 'E', 'E', 'K', 'S', 'F',
        'O', 'R', 'G', 'E', 'E', 'K', 'S']
print("Initial List: ")
print(List)

# Print elements from beginning
# to a pre-defined point using Slice
Sliced_List = List[:-6]
print("\nElements sliced till 6th element from last: ")
print(Sliced_List)

# Print elements of a range
# using negative index List slicing
Sliced_List = List[-6:-1]
print("\nElements sliced from index -6 to -1")
print(Sliced_List)

# Printing elements in reverse
# using Slice operation
Sliced_List = List[::-1]
print("\nPrinting List in reverse: ")
print(Sliced_List)

输出

Initial List: 
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']

Elements sliced till 6th element from last: 
['G', 'E', 'E', 'K', 'S', 'F', 'O']

Elements sliced from index -6 to -1
['R', 'G', 'E', 'E', 'K']

Printing List in reverse: 
['S', 'K', 'E', 'E', 'G', 'R', 'O', 'F', 'S', 'K', 'E', 'E', 'G']

列表理解

Python 列表推导式用于从其他可迭代对象(如元组、字符串、数组、列表等)创建新列表。列表推导式由包含表达式的括号组成,该表达式针对每个元素以及 for 循环执行以迭代每个元素。

句法:

newList = [ expression(element) for element in oldList if condition ]

例子:

# Python program to demonstrate list
# comprehension in Python

# below list contains square of all
# odd numbers from range 1 to 10
odd_square = [x ** 2 for x in range(1, 11) if x % 2 == 1]
print(odd_square)

输出

[1, 9, 25, 49, 81]

为了更好的理解,上面的代码类似如下:

# for understanding, above generation is same as,
odd_square = []

for x in range(1, 11):
    if x % 2 == 1:
        odd_square.append(x**2)

print(odd_square)

输出

[1, 9, 25, 49, 81]


原文链接:codingdict.net