python添加数组元素_Python列表附录–如何向数组添加元素,并附带示例说明
python添加数组元素
欢迎 (Welcome)
Hi! If you want to learn how to use the append()
method, then this article is for you. This is a powerful list method that you will definitely use in your Python projects.
嗨! 如果您想学习如何使用append()
方法,那么本文适合您。 这是一个功能强大的列表方法,您肯定会在Python项目中使用。
In this article, you will learn:
在本文中,您将学习:
Why and when you should use
append()
.为什么和何时应该使用
append()
。- How to call it.怎么称呼它。
- Its effect and return value.其效果和返回值。
How it can be equivalent to
insert()
and string slicing with the appropriate arguments.它如何等效于
insert()
和带有适当参数的字符串切片。
You will find examples of the use of append()
applied to strings, integers, floats, booleans, lists, tuples, and dictionaries.
您将找到append()
应用于字符串,整数,浮点数,布尔值,列表,元组和字典的示例。
Let's begin! 🔅
让我们开始! 🔅
目的 (Purpose)
With this method, you can add a single element to the end of a list.
使用此方法,您可以将单个元素添加到list的末尾 。
Here you can see the effect of append()
graphically:
在这里,您可以以图形方式看到append()
的效果:
💡 Tip: To add a sequence of individual elements, you would need to use the extend()
method.
提示:要添加单个元素的序列,您将需要使用extend()
方法。
语法和参数 (Syntax & Parameters)
This is the basic syntax that you need to use to call this method:
这是调用此方法所需的基本语法:
💡 Tip: The dot is very important since append()
is a method. When we call a method, we use a dot after the list to indicate that we want to "modify" or "affect" that particular list.
💡 提示:点非常重要,因为append()
是一种方法。 当我们调用一个方法时,我们在列表后使用一个点来表示我们要“修改”或“影响”该特定列表。
As you can see, the append()
method only takes one argument, the element that you want to append. This element can be of any data type:
如您所见, append()
方法仅接受一个参数,即您要附加的元素。 该元素可以是任何数据类型:
- Integer整数
- String串
- Float浮动
- Boolean布尔型
- Another list另一个清单
- Tuple元组
- Dictionary字典
- An Instance of a custom class自定义类的实例
Basically, any value that you can create in Python can be appended to a list.
基本上,您可以在Python中创建的任何值都可以附加到列表中。
💡 Tip: The first element of the syntax (the list) is usually a variable that references a list.
提示:语法的第一个元素(列表)通常是引用列表的变量。
例 (Example)
This is an example of a call to append()
:
这是对append()
的调用示例:
>>> musical_notes = ["C", "D", "E", "F", "G", "A"]
>>> musical_notes.append("B")
- First, the list is defined and assigned to a variable.首先,定义列表并将其分配给变量。
Then, using this variable we call the
append()
method, passing the element that we want to append (the string"B"
) as argument.然后,使用此变量,我们调用
append()
方法,并传递要添加的元素(字符串"B"
)作为参数。
效果与回报价值 (Effect & Return Value)
This method mutates (changes) the original list in memory. It doesn't return a new copy of the list as we might intuitively think, it returns None
. Therefore, just by calling this method you are modifying the original list.
这种方法变异 (变化)的原始列表在内存中。 它不会像我们直觉的那样返回列表的新副本,而是返回None
。 因此,仅通过调用此方法即可修改原始列表。
In our previous example:
在我们之前的示例中:
>>> musical_notes = ["C", "D", "E", "F", "G", "A"]
>>> musical_notes.append("B")
You can see (below) that the original list was modified after appending the element. The last element is now "B"
and the original list is now the modified version.
您可以看到(在下面)附加元素后原始列表已被修改。 现在,最后一个元素是"B"
,原始列表现在是修改后的版本。
>>> musical_notes
['C', 'D', 'E', 'F', 'G', 'A', 'B']
You can confirm that the return value of append()
is None
by assigning this value to a variable and printing it:
您可以通过将该值分配给变量并打印,来确认append()
的返回值为None
。
>>> musical_notes = ["C", "D", "E", "F", "G", "A"]
>>> a = musical_notes.append("B")
>>> print(a)
None
例子 (Examples)
Now that you know the purpose, syntax, and effect of the append()
method, let's see some examples of its use with various data types.
现在您知道了append()
方法的用途,语法和效果,让我们看一下将其用于各种数据类型的一些示例。
附加字符串 (Append a String)
>>> top_players = ["gino234", "nor233", "lal453"]
>>> top_players.append("auop342")# The string was appended
>>> top_players
['gino234', 'nor233', 'lal453', 'auop342']
附加整数 (Append an Integer)
>>> data = [435, 324, 275, 567, 123]
>>> data.append(456)>>> data
[435, 324, 275, 567, 123, 456]
追加浮动 (Append a Float)
>>> data = [435.34, 324.35, 275.45, 567.34, 123.23]
>>> data.append(456.23)>>> data
[435.34, 324.35, 275.45, 567.34, 123.23, 456.23]
附加布尔值 (Append a Boolean Value)
>>> values = [True, True, False, True]
>>> values.append(False)>>> values
[True, True, False, True, False]
追加清单 (Append a List)
This method appends a single element to the end of the list, so if you pass a list as argument, the entire list will be appended as a single element (it will be a nested list within the original list).
此方法将单个元素追加到列表的末尾,因此,如果将列表作为参数传递,则整个列表将作为单个元素追加(它将是原始列表内的嵌套列表)。
>>> data = [[4.5, 4.8, 5.7], [2.5, 2.6, 2.7]]
>>> data.append([6.7, 2.3])>>> data
[[4.5, 4.8, 5.7], [2.5, 2.6, 2.7], [6.7, 2.3]]
追加元组 (Append a Tuple)
This works exactly the same for tuples, the entire tuple is appended as a single element.
对于元组,这完全相同,整个元组作为单个元素附加。
>>> data = [[4.5, 4.8, 5.7], [2.5, 2.6, 2.7]]
>>> data.append((6.7, 2.3))>>> data
[[4.5, 4.8, 5.7], [2.5, 2.6, 2.7], (6.7, 2.3)]
💡 Tip: If you need to add the elements of a list or tuple as individual elements of the original list, you need to use the extend()
method instead of append()
. To learn more about this, you can read my article: Python List Append VS Python List Extend – The Difference Explained with Array Method Examples
提示:如果需要将列表或元组的元素添加为原始列表的单个元素,则需要使用extend()
方法而不是append()
。 要了解更多信息,请阅读我的文章: Python列表附加VS Python列表扩展–数组方法示例的差异解释
追加字典 (Append a dictionary )
Similarly, if you try to append a dictionary, the entire dictionary will be appended as a single element of the list.
同样,如果您尝试追加字典,则整个字典将作为列表的单个元素追加。
>>> data = [{"a": 1, "b": 2}]
>>> data.append({"c": 3, "d": 4})
>>> data
[{'a': 1, 'b': 2}, {'c': 3, 'd': 4}]
追加和插入的等效性 (Equivalence of Append and Insert )
An interesting tip is that the insert()
method can be equivalent to append()
if we pass the correct arguments.
一个有趣的提示是,如果我们传递正确的参数, insert()
方法可以等效于append()
。
The insert()
method is used to insert an element at a particular index (position) in the list.
insert()
方法用于将元素插入列表中的特定索引(位置)。
This is the syntax used to call the insert()
method:
这是用于调用insert()
方法的语法:
To make it equivalent to append()
:
使它等效于append()
:
The value of index has to be the length of the list (
len(<list>)
) because we want the element to be the last element of the list.index的值必须是列表的长度(
len(<list>)
),因为我们希望该元素成为列表的最后一个元素。
Here's an example that shows that the result of using insert with these arguments is equivalent to append()
:
这是一个示例,显示使用带有这些参数的insert的结果等效于append()
:
>>> musical_notes = ["C", "D", "E", "F", "G", "A"]
>>> musical_notes.insert(len(musical_notes), "B")
>>> musical_notes
['C', 'D', 'E', 'F', 'G', 'A', 'B']
But as you have seen, append()
is much more concise and practical, so it's usually recommended to use it in this case.
但是如您所见, append()
更加简洁实用,因此通常建议在这种情况下使用它。
追加和列表切片的等效性 (Equivalence of Append and List Slicing)
There is also an interesting equivalence between the append()
method and list slicing.
append()
方法和列表切片之间也有一个有趣的等效项。
This syntax is essentially assigning the list that contains the element [<elem>]
as the last portion (end) of the list. Here you can see that the result is equivalent to append()
:
此语法实质上是将包含元素[<elem>]
的列表分配为列表的最后一部分(结尾)。 在这里,您可以看到结果等同于append()
:
>>> musical_notes = ["C", "D", "E", "F", "G", "A"]
>>> musical_notes[len(musical_notes):] = ["B"]
>>> musical_notes
['C', 'D', 'E', 'F', 'G', 'A', 'B']
These are interesting alternatives, but for practical purposes we typically use append()
because it's a priceless tool that Python offers. It is precise, concise, and easy to use.
这些是有趣的替代方法,但是出于实际目的,我们通常使用append()
因为它是Python提供的无价工具。 它精确,简洁且易于使用。
I really hope that you liked my article and found it helpful. Now you can work with append()
in your Python projects. Check out my online courses. Follow me on Twitter. 👍
我真的希望您喜欢我的文章并发现它对您有所帮助。 现在,您可以在Python项目中使用append()
。 查看我的在线课程 。 在Twitter上关注我。 👍
翻译自: https://www.freecodecamp.org/news/python-list-append-how-to-add-an-element-to-an-array-explained-with-examples/
python添加数组元素
相关文章:

学习进度条--第七周
第七周 所花时间(包括上课时间) 10小时(包括上课2小时) 代码量(行) 152 博客量(篇) 2篇(包括团队博客) 了解到的知识点 对组内开发的软件进行讨论&am…

Mybatis获取插入记录的自增长ID
转自:http://blog.csdn.net/tolcf/article/details/39035259 1.在Mybatis Mapper文件中添加属性“useGeneratedKeys”和“keyProperty”,其中keyProperty是Java对象的属性名,而不是表格的字段名。 <insert id"insert" parameter…

android中一种不支持的lua操作
今天写了一段lua代码,在win32中正常运行,在android中运行无效。 大概是这样的: ------file1.lua----- local t {} t.str "this is file1.t" return t ---------------------- -----file2.lua------ local t require &quo…

23岁一无所有怎么办_我搬到国外去创业,然后一无所有。
23岁一无所有怎么办以我的名字还不到一美元,它仍然感觉不像是最低点。 (With not even a dollar to my name, it still didn’t feel like rock bottom.) When you tell someone you’re working for a startup, they’ll either think you’re gonna be really ric…

正则表达式的基本入门
一、正则表达式基本语法 1. 两个特殊的符号‘^’和‘$’。他们的作用分别指出一个字符串的开始和结束。 2. 其他还有‘*’,‘’,‘?’这三个符号,表示一个或一序列字符重复出现的次数 "ab{2}" ---表示一个字符串有一个…

多继承中虚基类构造函数的一种调用规则
规则:如果父类中有虚基类(A),且有一个直接基类(B)是虚基类的子类,那么子类(C或D)若不显式调用虚基类的有参数构造函数,它的直接基类(B)即使在构造列表中调用了非默认构造函数,那么也会直接调用虚基类的默认构造函数。 …

Android 常见异常及解决办法
前言 本文主要记录 Android 的常见异常及解决办法,以备以后遇到相同问题时可以快速解决。 1. java.lang.NullPointerException: Attempt to invoke virtual method void android.widget.TextView.setText(java.lang.CharSequence) on a null object reference 1) …
aws s3 静态网站_如何将静态网站或JAMstack应用托管并部署到AWS S3和CloudFront
aws s3 静态网站S3 and CloudFront are AWS cloud services that make serving static assets powerful and cheap. How can we host a simple static website or JAMstack app on it?S3和CloudFront是AWS云服务,使服务静态资产功能强大且价格便宜。 我们如何在其上…

图像预处理第7步:标准归一化
图像预处理第7步:标准归一化将分割出来的各个不同宽、高的数字字符宽、高统一 //图像预处理第7步:标准归一化 //将分割出来的各个不同宽、高的数字字符宽、高统一 void CChildView::OnImgprcStandarize() {StdDIBbyRect(m_hDIB,w_sample,h_sample);//在…

8. 进制转化的函数
一,表示进制的单词 bin:二进制 oct:八进制 dec:十进制 hex:十六进制二,四种进制的数据表示方式 $bin0b1010; //二进制数字写法(暂时不学 ) …

二叉树广度优先遍历
#include <iostream> using namespace std;struct Node{//二叉树节点int value;Node *left;Node *right; };struct queue{//辅助队列int head;int tail;int len;//队列长度,遍历时用Node ** list;//队列内容void push(Node *n){list[tail] n;len;}Node * pop…

phaser.min.js_如何使用Phaser 3,Express和Socket.IO构建多人纸牌游戏
phaser.min.jsIm a tabletop game developer, and am continually looking for ways to digitize game experiences. In this tutorial, were going to build a multiplayer card game using Phaser 3, Express, and Socket.IO.我是桌面游戏开发人员,并且一直在寻找…

VirtualBox - RTR3InitEx failed with rc=-1912 (rc=-1912)
有一天重启电脑后虚拟机virtual box突然打不开了,提示类似 https://askubuntu.com/questions/900794/virtualbox-rtr3initex-failed-with-rc-1912-rc-1912 参考帖子中查看了一下包的情况dpkg --list virtualbox-* | grep ii 结果:ii virtualbox-dkms …

边工作边刷题:70天一遍leetcode: day 27
Permutation Sequence 原理:一个permutation是n位,在第i位的值取决于有多少个i-1位的组合。这i-1位的组合是在高位pick完之后剩下的数中 细节: 不同于decimal,位数是固定的,所以不能用k>0作为循环条件(这…

基本数据结构(图: 基本结构,DFS,prim算法, kruskal算法)
#include <iostream> using namespace std; //约定: //1. 图是由很多节点(VERTEX)构成的, 因此图结构是由一个VERTEX的链表构成的, 每个VERTEX则需要有一个id,也就是start, 取start是为了跟LINE更直观地结合。 //2. 每个节点关联着很多(LINE)构成,因此每个VER…
gatsby_如何使用Gatsby和Leaflet创建夏季公路旅行地图绘制应用程序
gatsbyGet ready for the summer by building your own road trip mapping app with this step-by-step guide!通过此逐步指南,构建自己的公路旅行地图应用,为夏天做好准备! What are we going to build? 我们要建造什么? What …

NEFU 1146 又见A+B
又见ab Problem:1146 Time Limit:1000ms Memory Limit:65535K Description 给定两个非负整数A,B,求他们的和。 Input 多组输入,每组输入两个非负整数A和B(0<A,B<10^3000),可能会有前缀0,但保证总长度不超过3000…

图的最短路径dijkstra算法
想法是这样的: 1. 最开始要建立4个list,分别存储 a. 所有的Vertex: allVertex[] b. 一个空的Vertex list: emptyVertex[] c. 一个前缀表 previous list(用来回溯路径用): previous[] d. 一个表示最短距离的表(就是表示某个点与0点的最短距离)࿱…

JDBC数据源连接池(1)---DBCP
何为数据源呢?也就是数据的来源。我在前面的一篇文章《JDBC原生数据库连接》中,采用了mysql数据库,数据来源于mysql,那么mysql就是一种数据源。在实际工作中,除了mysql,往往还会有Oracle,sql se…
如果成为一名高级安卓开发_什么是高级开发人员,我如何成为一名开发人员?
如果成为一名高级安卓开发Becoming a Senior Developer is something many of us strive for as we continue our code journey and build our career. But what does it actually mean to be a "Senior" Developer?成为一名高级开发人员是我们许多人在继续我们的代…

拍牌神器是怎样炼成的(三)---注册全局热键
要想在上海拍牌的超低中标率中把握机会、占得先机,您不仅需要事先准备好最优的竞拍策略,还要制定若干套应急预案,应对不时之需。既定策略交给计算机自动执行,没有问题。可是谁来召唤应急预案呢?使用全局热键应该是个不…

eclipse 变成中文
官方下载 http://www.eclipse.org/babel/downloads.php 按照自己的eclipse版本下载对应的 复制链接 到eclipse ->help->Install New Software 勾选自己的语言包 如: 等待 安装完成 ,无过不好用 更改 右键 属性 更改位置 加后缀 D:\xinle_eclips…

框架模式与设计模式之区别
http://my.oschina.net/u/991183/blog/109854 有很多程序员往往把框架模式和设计模式混淆,认为MVC是一种设计模式。实际上它们完全是不同的概念。框架、设计模式这两个概念总容易被混淆,其实它们之间还是有区别的。框架通常是代码重用,而设计…
村上春树 开始写作_如何克服对写作的恐惧并找到开始的动力
村上春树 开始写作Writing about our work is one of those things that most of us have on our to-do list. But whether its due to procrastination or fear, we never actually get to it. Heres some more motivation and reasons why you should give it a shot!撰写我们…

一个基于组件的动态对象系统
http://hulefei29.iteye.com/blog/1490889 一、静态的痛苦 作为一个项目经验丰富的程序员,你经常会遇到游戏开发过程中的“反复”(iterations):今天美术将一个静态的模型改为骨骼模型并添加了动画;明天企划会议上决定把所有未拾取武器由…

Lua生成Guid(uuid)
全局唯一标识符(GUID,Globally Unique Identifier)也称作 UUID(Universally Unique IDentifier) 。GUID是一种由算法生成的二进制长度为128位的数字标识符。GUID主要用于在拥有多个节点、多台计算机的网络或系统中。在理想情况下,…

c:if标签的使用
1、标签的基本介绍 <c:if> 标签必须要有test属性,当test中的表达式结果为true时,则会执行本体内容;如果为false,则不会执行。例如:${requestScope.username admin},如果requestScope.username等adm…

ecs和eks 比较_如何使用Kubernetes,EKS和NGINX为网站设置DNS
ecs和eks 比较As the creator of Foo, a platform for website quality monitoring, I recently endeavored in a migration to Kubernetes and EKS (an AWS service).作为网站质量监控平台Foo的创建者,我最近努力迁移到Kubernetes和EKS(一种AWS服务)。 Kubernetes…

仅需6步,教你轻易撕掉app开发框架的神秘面纱(1):确定框架方案
遇到的问题 做游戏的时候用的是cocos2dxlua,游戏开发自有它的一套框架机制。而现在公司主要项目要做android和iOS应用。本文主要介绍如何搭建简单易用的App框架。 如何解决 对于新手来说,接触一门新的知识,往往会思考该怎么入手,…

js全局变量污染
一.定义全局变量命名空间 只创建一个全局变量,并定义该变量为当前应用容器,把其他全局变量追加在该命名空间下 var my{}; my.name{big_name:"zhangsan",small_name:"lisi" }; my.work{school_work:"study",family_work:&q…