百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

Python列表(List)(python列表list[0][1])

off999 2024-10-16 11:25 19 浏览 0 评论

列表(Lists)就像用其他语言声明的数组一样。列表不一定总是同质的,这使其成为Python中最强大的工具。单个列表可能包含数据类型,例如整数,字符串以及对象。列表是可变的,因此即使在创建后也可以对其进行更改。

Python中的List是有序的,并且有一个确定的计数。列表中的元素按照一定的顺序进行索引,并且列表的索引是在0为第一个索引的情况下完成的。列表中的每个元素在列表中都有其明确的位置,这允许复制列表中的元素,每个元素都有其独特的位置和可信度。

注意:列表是用于保留数据序列并对其进行进一步迭代的有用工具。

创建列表

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

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

# Python program to demonstrate  
# Creation of List  
  
# Creating a List 
List = [] 
print("Intial blank List: ") 
print(List) 
  
# Creating a List with  
# the use of a String 
List = ['GeeksForGeeks'] 
print("\nList with the use of String: ") 
print(List) 
  
# Creating a List with 
# the use of multiple values 
List = ["Geeks", "For", "Geeks"] 
print("\nList containing multiple values: ") 
print(List[0])  
print(List[2]) 
  
# Creating a Multi-Dimensional List 
# (By Nesting a list inside a List) 
List = [['Geeks', 'For'] , ['Geeks']] 
print("\nMulti-Dimensional List: ") 
print(List) 

输出:

Intial blank List: 
[]

List with the use of String: 
['GeeksForGeeks']

List containing multiple values: 
Geeks
Geeks

Multi-Dimensional List: 
[['Geeks', 'For'], ['Geeks']]

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

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

# 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) 

输出:

List with the use of Numbers: 
[1, 2, 4, 4, 3, 3, 3, 6, 5]

List with the use of Mixed Values: 
[1, 2, 'Geeks', 4, 'For', 6, 'Geeks']

向列表中添加元素

使用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']]

使用insert()方法

append()方法只适用于在列表末尾添加元素,对于在所需位置添加元素,则使用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]

使用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']

访问列表中的元素

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

# 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]) 
  
# Creating a Multi-Dimensional List 
# (By Nesting a list inside a List) 
List = [['Geeks', 'For'] , ['Geeks']] 
  
# accessing a element from the  
# Multi-Dimensional List using 
# index number 
print("Acessing a element from a Multi-Dimensional list") 
print(List[0][1]) 
print(List[1][0]) 

输出:

Accessing a element from the list
Geeks
Geeks

Acessing 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 a element using 
# negative indexing 
print("Acessing element using negative indexing") 
  
# print the last element of list 
print(List[-1]) 
  
# print the third last element of list  
print(List[-3]) 

输出:

Acessing element using negative indexing
Geeks
For

从列表中删除元素

使用remove()方法

可以使用内置的remove()函数从列表中删除元素,但是如果元素不存在于集合中,则会发生错误。Remove()方法一次只删除一个元素,要删除元素范围,则使用迭代器。remove()方法删除指定的项目。

注意:列表中的Remove方法将只删除搜索到的元素的第一个匹配项。

# 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("Intial 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) 
  
# 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) 

输出:

Intial 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]

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

使用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]

列表切片(Slicing of a List)

在Python List中,有多种方法可以打印包含所有元素的整个列表,但是要从列表中打印特定范围的元素,我们使用Slice操作。切片操作在使用冒号(:)的列表上执行。若要从开始到范围打印元素,请使用[:Index];若要从结束使用[:-Index]打印元素;若要从特定索引打印元素,直到结束使用[Index:];若要打印范围内的元素,请使用[开始索引:结束索引];若要使用切片操作打印整个列表,请使用[:]。此外,要按相反顺序打印整个列表,请使用[::-1]。

注意:要从后端打印列表元素,请使用负索引。

# 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("Intial 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) 

输出:

Intial 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函数参数和返回值类型:让你的代码更清晰、更健壮

在Python开发中,你是否遇到过这些抓狂时刻?同事写的函数参数类型全靠猜调试两小时发现传了字符串给数值计算函数重构代码时不知道函数返回的是列表还是字典今天教你两招,彻底解决类型混乱问题!让你的...

有公司内部竟然禁用了python开发,软件开发何去何从?

今天有网友在某社交平台发文:有公司内部竟然禁止了python开发!帖子没几行,评论却炸锅了。有的说“太正常,Python本就不适合做大项目”,还有的反驳“飞书全员用Python”。暂且不说这家公司...

写 Python 七年才发现的七件事:真正提高生产力的脚本思路

如果你已经用Python写了不少脚本,却总觉得代码只是“能跑”,这篇文章或许会刷新你对这门语言的认知。以下七个思路全部来自一线实战,没有花哨的概念,只有可落地的工具与习惯。它们曾帮我省下大量无意义...

用Python写一个A*搜索算法含注释说明

大家好!我是幻化意识流。今天我们用Python写一个A*搜索算法的代码,我做了注释说明,欢迎大家一起学习:importheapq#定义搜索节点类,包括当前状态、从初始状态到该状态的代价g、从该状态...

使用python制作一个贪吃蛇游戏,并为每一句添加注释方便学习

今天来设计一个贪吃蛇的经典小游戏。先介绍下核心代码功能(源代码请往最后面拉):游戏功能:-四个难度等级:简单(8FPS)、中等(12FPS)、困难(18FPS)、专家(25FPS)-美...

Python 之父 Guido van Rossum 宣布退休

Python之父GuidovanRossum在推特公布了自己从Dropbox公司离职的消息,并表示已经退休。他还提到自己在Dropbox担任工程师期间学到了很多东西——Python的类型注解(T...

4 个早该掌握的 Python 类型注解技巧

在Python的开发过程中,类型注解常常被忽视。但当面对一段缺乏类型提示、逻辑复杂的代码时,理解和维护成本会迅速上升,极易陷入“阅读地狱”。本文整理了4个关于Python类型注解的重要技巧...

让你的Python代码更易读:7个提升函数可读性的实用技巧

如果你正在阅读这篇文章,很可能你已经用Python编程有一段时间了。今天,让我们聊聊可以提升你编程水平的一件事:编写易读的函数。请想一想:我们花在阅读代码上的时间大约是写代码的10倍。所以,每当你创建...

Python异常模块和包

异常当检测到一个错误时,Python解释器就无法继续执行了,反而出现了一些错误的提示,这就是所谓的“异常”,也就是我们常说的BUG例如:以`r`方式打开一个不存在的文件。f=open('...

别再被 return 坑了!一文吃透 Python return 语句常见错误与调试方法

Pythonreturn语句常见错误与调试方法(结构化详解)一.语法错误:遗漏return或返回值类型错误错误场景pythondefadd(a,b):print(a+b)...

Python数据校验不再难:Pydantic库的工程化实践指南

在FastAPI框架横扫Python后端开发领域的今天,其默认集成的Pydantic库正成为处理数据验证的黄金标准。这个看似简单的库究竟隐藏着哪些让开发者爱不释手的能力?本文将通过真实项目案例,带您解...

python防诈骗的脚本带注释信息

以下是一个简单但功能完整的防诈骗脚本,包含URL检测、文本分析和风险评估功能。代码结构清晰,带有详细注释,适合作为个人或家庭防诈骗工具使用。这个脚本具有以下功能:文本诈骗风险分析:检测常见诈骗关键...

Python判断语句

布尔类型和比较运算符布尔类型的定义:布尔类型只有两个值:True和False可以通过定义变量存储布尔类型数据:变量名称=布尔类型值(True/False)布尔类型不仅可以自行定义,同时也可通过...

使用python编写俄罗斯方块小游戏并为每一句添加注释,方便学习

先看下学习指导#俄罗斯方块游戏开发-Python学习指导##项目概述这个俄罗斯方块游戏是一个完整的Python项目,涵盖了以下重要的编程概念:-面向对象编程(OOP)-游戏开发基础-数据...

Python十大技巧:不掌握这些,你可能一直在做无用功!

在编程的世界里,掌握一门语言只是起点,如何写出优雅、高效的代码才是真功夫。Python作为最受欢迎的编程语言之一,拥有简洁明了的语法,但要想真正精通这门语言,还需要掌握一些实用的高级技巧。一、列表推导...

取消回复欢迎 发表评论: