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个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值