python中定义数据结构
This article is about lists. They are the most versatile and resourceful, in-built data structure in Python. They can simultaneously hold heterogeneous data i.e., integers, floats, strings, NaN, Booleans, functions, etc. within the same list. They are an ordered sequence of items that means the order of the elements is preserved while accessing lists. They are mutable i.e., you can change (add, delete, modify) any item in the list. They can hold duplicate items unlike “sets” — another data structure in Python.
本文是关于列表的 。 它们是Python中功能最多,资源最丰富的内置数据结构 。 它们可以同时保存异构数据,即同一列表中的整数,浮点数,字符串,NaN,布尔值,函数等。 它们是项目的有序序列,这意味着在访问列表时会保留元素的顺序。 它们是可变的,即您可以更改 (添加,删除,修改)列表中的任何项目。 他们可以保留与“集合”不同的重复项,而“集合”是Python中的另一种数据结构。
After reading this article, you will gain a clear understanding and ability to work at an advanced level with Python lists.
阅读本文之后,您将获得对Python列表的更深入的了解和更高级的工作能力。
I will cover the following topics:
我将介绍以下主题:
-
Creating a list and adding elements
创建列表并添加元素
-
Accessing list elements
访问列表元素
-
Removing list elements
删除列表元素
-
Inserting elements
插入元素
-
List arithmetic
列表算术
-
Reversing a list
倒转清单
-
Sorting a list
排序清单
-
Index of an item
项目索引
-
Counting item frequency in a list
计算列表中的项目频率
-
List comprehensions
清单理解
-
Copying a list
复制清单
-
Nested lists
嵌套列表
1)创建一个列表并添加元素 (1) Creating a list and adding elements)
First, we initialize an empty list called “data”. The list is created using square brackets. Naturally, the length of an empty list is zero.
首先,我们初始化一个称为“数据”的空列表 。 该列表使用方括号创建。 自然,空列表的长度为零。
data = []len(data)
>>> 0# Check the type of the variable 'data'
type(data)
>>> list
Now let’s add our very first element to this list. This is done using the append() function. You will notice that its length now becomes one.
现在,让我们将第一个元素添加到此列表中。 这是使用append()函数完成的。 您会注意到它的长度现在变为1。
data.append(100)data
>>> [100]len(data)
>>> 1
Let’s add a second element. It will be appended (added) at the end of the list. Similarly, you can append as many elements as you want.
让我们添加第二个元素。 它将被添加(添加)在列表的末尾。 同样,您可以根据需要附加任意数量的元素。
data.append(200)
data
>>> [100, 200]len(data)
>>> 2data.append(300)
data
>>> [100, 200, 300]
The append function is useful when you do not know beforehand how many elements will be in your list. For example, to store the number of people entering a shop every hour, you need to append the number of customers on an hourly basis. However, if you just hosted an exam, you know exactly how many students wrote the exam. Now, if you want to store their grades in a list, instead of appending, you can just initialize your list altogether.
当您事先不知道列表中有多少个元素时, append函数很有用。 例如,要存储每小时进入商店的人数,您需要每小时附加一次客户数量。 但是,如果您只是主持考试,则可以确切知道有多少学生参加了考试。 现在,如果要将其成绩存储在列表中,而不是追加,则可以完全初始化列表。
grades = [70, 100, 97, 67, 85]len(grades)
>>> 5
Don’t worry! You can still add more elements to your already initialized list using append. Just simply use data.append(80) to add the grades of a sixth student afterward and it will be appended at the end of the list.
不用担心 您仍然可以使用append将更多元素添加到已初始化的列表中。 只需简单地使用data.append(80)添加第六名学生的成绩,它就会被添加到列表的末尾。
如何一次添加两个或更多学生的分数? (How to add the marks of two or more students at once?)
Suppose you want to append marks of three students simultaneously. You cannot use grades.append(99, 100, 95) because “append” takes exactly one argument. You will have to use the “append” function three times.
假设你想同时追加三个学生的痕迹。 您不能使用grades.append(99,100,95),因为“ append”仅接受一个参数 。 您将不得不使用“附加”功能三次。
Rather than appending three times, you can use extend() in such cases. You need to put the three elements in a tuple form (an iterable).
在这种情况下,您可以使用extend()而不是附加三次。 您需要将三个元素以元组形式(可迭代)放置。
Note that you cannot use extend for appending a single element i.e., data.extend((90)) won't work.
请注意,您不能将扩展用于附加单个元素,即data.extend((90))将不起作用。
grades = [70, 100, 97, 67, 85]
grades.extend((99, 100, 95))
print (grades)
>>> [70, 100, 97, 67, 85, 99, 100, 95]
现在您会问:“为什么我们不能一次添加三个年级?” (Now you will ask, “Why can’t we append three grades at once?”)
You can, but there is a catch. As shown below, the three grades inserted together show up as a list inside the main list. Such lists are called “Nested Lists”. I will show more examples in the last section of this article.
可以, 但是有一个陷阱 。 如下所示,插入在一起的三个年级在主列表中显示为一个列表。 这样的列表称为“嵌套列表” 。 我将在本文的最后一部分中显示更多示例。
grades = [70, 100, 97, 67, 85]
grades.append([99, 100, 95])
print (grades)
>>> [70, 100, 97, 67, 85, [99, 100, 95]] # A nested list
2)访问列表元素 (2) Accessing list elements)
If you are working with data structures, it is very useful to know the concept of indexing. You can think of indexing as a serial number assigned to each element of the list. Simply put, it is similar to your roll numbers in a class.
如果 您正在使用数据结构时,了解概念非常有用 索引 。 您可以将索引视为分配给列表的每个元素的序列号 。 简而言之,它类似于您在课程中的卷数。
The most important thing to know is that indexing in Python starts at 0.
要知道 的 最重要的 事情是 Python 中的 索引从0开始 。
So, the first element will have an index of 0, the second element will have an index of 1, and so on. In a list of five elements, the last (fifth) element will have an index value of 4.
因此,第一个元素的索引为0,第二个元素的索引为1,依此类推。 在五个元素的列表中,最后一个(第五个)元素的索引值为4。
grades = [70, 100, 97, 67, 85]# First element (index 0)
grades[0]
>>> 70# Second element (index 1)
grades[1]
>>> 100# Last element (index 4)
grades[4]
>>> 85
Do not cross the limits. If you try to use an index value that is greater than the length of the list, you will get an IndexError. So, in a list of 5 elements, you cannot use an index of 5 (since it refers to the sixth element).
不要越过界限。 如果您尝试使用大于列表长度的索引值,则会得到IndexError 。 因此,在5个元素的列表中,不能使用5的索引(因为它引用了第六个元素)。
grades[5]-----------------------------------------------------------------IndexError Traceback (most recent call last)<ipython-input-29-d8836f1h2p9> in <module>----> 1 data[5]IndexError: list index out of range
访问列表中的多个元素 (Accessing multiple elements of the list)
If you want the first three elements, you can access them using slicing. The general format is list[start_index:end_index]. The tricky part here is that this notation will return the values until the index value of end_index - 1. It means, to get the first three elements of the list that has indices 0, 1, and 2, you need the following way.
如果需要前三个元素,则可以使用slicing访问它们。 通用格式为list[start_index:end_index] 。 棘手的部分 此处表示法将返回这些值,直到end_index-1的索引值为止。 这意味着,要获取具有索引0、1和2的列表的前三个元素,您需要采用以下方式。
grades = [70, 100, 97, 67, 85]
grades[0:3]
>>> [70, 100, 97]
If you want to only access the first element having index 0, you can get it using the slicing notation.
如果只想访问索引为0的第一个元素,则可以使用切片符号获取它。
grades[0:1]
>>> [70]
反向索引 (Reverse Indexing)
It’s time you should also know the helpful concept of what I call “Reverse indexing” or “Negative indexing”.
是时候您也应该知道所谓的“反向索引”或“负索引”的有用概念了。
To access the last element, you first need to know the length of the list. So, in a list of 5 elements, you need to use index 4 (= 5–1 because indexing starts at 0). So, data[4] will be your last element. Similarly, the second last element will be data[3], and so on.
要访问最后一个元素,您首先需要知道列表的长度。 因此,在5个元素的列表中,您需要使用索引4(= 5–1,因为索引从0开始)。 因此,data [4]将是您的最后一个元素。 同样,倒数第二个元素将是data [3],依此类推。
As you can see, this computation is cumbersome. Negative indexing will help you here. Simply count the number of elements from the end. The last element cannot be at index -0 as there is no such number. Hence, you need to access it using the index value of -1. Similarly, the second last element can be accessed using the index value of -2, and so on.
如您所见,这种计算很麻烦。 负索引将在这里为您提供帮助。 只是 从头算起元素的数量。 最后一个元素不能在索引-0处,因为没有这样的数字。 因此,您需要使用索引值-1访问它。 同样,可以使用索引值-2等访问倒数第二个元素。
grades = [70, 100, 97, 67, 85]
grades[-1]
>>> 85grades[-2]
>>> 67
“可以使用负索引来访问最后三个元素吗?”。 (“Can the negative indices be used to access the last 3 elements?”.)
Yes. You need to specify the starting negative indexing. To get all the elements from the third last element onwards, you don’t need to specify the end index.
是。 您需要指定开始的负索引。 要从倒数第二个元素开始获取所有元素,无需指定结束索引。
grades = [70, 100, 97, 67, 85]
grades[-3:]
>>> [97, 67, 85]
However, suppose you want to get the third last and the second last element but not the last element. You can restrict the end index as:
但是,假设您要获取倒数第三和倒数第二个元素,而不是最后一个元素。 您可以将结束索引限制为:
grades[-3:-1]
>>> [97, 67]
2.1)定期访问元素 (2.1) Accessing elements at regular intervals)
So far you learned how to access either a single element or several consecutive elements. Suppose you want to get every n-th item from the list. The general syntax to do so islist[start_index : stop_index : step].
到目前为止,您已经学习了如何访问单个元素或几个连续元素。 假设您要从列表中获取第n个项目。 这样做的一般语法是list[start_index : stop_index : step] 。
Example: If you want to access every second element starting from the first element until the seventh element, i.e., from [1, 2, 3, 4, 5, 6, 7], you need [1, 3, 5, 7].
示例:如果要访问从第一个元素到第七个元素的第二个元素,即从[1、2、3、4、5、6、7],则需要[1、3、5、7] 。
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
data[0:7:2]
>>> [1, 3, 5, 7]
If you want every second element from the whole list starting from the first element, you can skip both, the start_index and the stop_index.
如果希望整个列表中的每个第二个元素都从第一个元素开始,则可以跳过start_index和stop_index 。
data[::2]
>>> [1, 3, 5, 7, 9]
If you want every second element from the whole list starting from the second element, use the following code.
如果要从第二个元素开始的整个列表中的每个第二个元素,请使用以下代码。
data[1::2]
>>> [2, 4, 6, 8, 10]
Note: You can also access the whole list using data[::1] because this will return every element from the start until the end.
注意:您也可以使用data[::1]访问整个列表,因为这将从头到尾返回每个元素。
Traversing a list backward at regular intervalYou need to use a negative step value. To get every element starting from the end i.e., the reverse of the whole list, use the following code.
定期向后遍历列表需要使用负步长值。 要使每个元素从头开始,即整个列表的相反,请使用以下代码。
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
data[::-1]
>>> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
To access every second element starting from the last, use the following code.
要从最后一个元素开始访问第二个元素,请使用以下代码。
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
data[::-2]
>>> [10, 8, 6, 4, 2]
Let’s look at a more complex reverse traversing example. Suppose you want to start from the third last element, go until the fourth element, and select every second element. Your start index now becomes -3 and the stop index becomes 3 (index of the fourth element as indexing starts at 0).
让我们看一个更复杂的反向遍历示例。 假设 您要从倒数第三个元素开始,一直到第四个元素,然后选择每隔一个元素。 现在,您的起始索引变为-3,终止索引变为3(随着索引从0开始,第四个元素的索引)。
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
data[-3:3:-2]
>>> [8, 6]
3)删除列表元素 (3) Removing list elements)
There are three ways to remove elements from a list. All three methods perform the in-place deletion i.e., after the deletion, you do not need to reassign the list to a new variable.
有三种方法可以从列表中删除元素。 所有这三种方法都执行就地删除,即在删除之后,您无需将列表重新分配给新变量。
a) del (in-built function) — Can delete multiple items at onceb) remove() (list’s method) — Can delete one item at a timec) pop() (list’s method) — Can delete one item at a time
a) del (内置函数)-可以一次删除多个项目 b) remove() (列表的方法)-可以一次删除一项 c) pop() (列表的方法)-一次可以删除一项
Let’s study them one by one.
让我们一一研究它们。
a)删除 (a) del)
While using del, you need to pass the index or a slice of indices of the elements to delete. You can use all the above-introduced concepts of indexing/slicing to delete the elements using del.
使用del ,您需要传递要删除的元素的索引或索引切片。 您可以使用上述所有引入的索引/切片概念来使用del删除元素。
# Deleting first element
data = [79, 65, 100, 85, 94]
del data[0]
print (data)
>>> [65, 100, 85, 94] ############################################################## Deleting second last element
data = [79, 65, 100, 85, 94]
del data[-2]
print (data)
>>> [79, 65, 100, 94]############################################################# # Deleting multiple consecutive elements using slice
data = [79, 65, 100, 85, 94]
del data[0:3]
print (data)
>>> [85, 94]############################################################## # Deleting multiple elements at regular interval using slice
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
del data[1::2]
data
# [1, 3, 5, 7, 9]
b)remove() (b) remove())
This method is used to remove a specific element from a list. If an element appears more than once, then only the first occurrence of this element will be deleted. For example, in the list below, 1 appears 3 times. So using remove(1) would remove the very first value and keep the rest.
此方法用于从列表中删除特定元素 。 如果一个元素出现多次,则只会删除该元素的第一次出现 。 例如,在下面的列表中,1出现3次。 因此,使用remove(1)会删除第一个值并保留其余值。
data = [1, 1, 4, 4, 3, 1, 3, 2, 4, 2]
data.remove(1)
print (data)
>>> [1, 4, 4, 3, 1, 3, 2, 4, 2]
BONUS: You can use a while loop to remove all the occurrences of 1.
奖励:您可以使用while循环删除所有出现的1。
data = [1, 1, 4, 4, 3, 1, 3, 2, 4, 2]
to_del = 1while to_del in data:
data.remove(to_del)
print (data)
>>> [4, 4, 3, 3, 2, 4, 2]
c)pop() (c) pop( ))
The syntax of this method is list.pop(i) that pops (deletes) the element at index ‘i’ from the list. The following code demonstrates how it works when applied successively to a list.
此方法的语法是list.pop(i) ,它会弹出(删除)索引“ i”处的元素 从列表中。 下面的代码演示了将其连续应用于列表时的工作方式。
Note: If you don’t specify an index, the last element will be removed.
注意:如果不指定索引,则最后一个元素将被删除。
# Using pop(i) by specifying the index i
data = [1, 2, 3, 4, 5]
data.pop(0)
print (data)
>>> [2, 3, 4, 5]data.pop(1)
print (data)
>>> [2, 4, 5]data.pop(1)
print (data)
>>> [2, 5]############################################################## Using pop() without specifying the index i
data = [1, 2, 3, 4, 5]
data.pop()
print (data)
>>> [1, 2, 3, 4]data.pop()
print (data)
>>> [1, 2, 3]
4)插入元素 (4) Inserting elements)
An element can be inserted at a specified location using the function list.insert(i, element). Here ‘i’ is the index of the existing element in the list before which you want to insert the element. As you saw earlier, the append() function inserts the element at the end of the list.
可以使用功能list.insert(i, element)将元素插入指定位置。 这里的“ i”是列表中现有元素的索引,您想在该索引之前插入该element 。 如前所述, append()函数将元素插入列表的末尾。
Note: This is an in-place operation so you don’t have to re-assign the list.
注意:这是就地操作,因此您不必重新分配列表。
# Inserting value of 4 at the start, before the element at index 0
data = [1, 2, 3]
data.insert(0, 4)
print (data)
>>> [4, 1, 2, 3]############################################################## Inserting value of 4 before the element at index 1
data = [1, 2, 3]
data.insert(1, 4)
print (data)
>>> [1, 4, 2, 3]
If you want to insert at the end of the list, i.e., kind of append, then simply use the length of the list as the place to insert.
如果要插入列表的末尾(即追加类型),则只需使用列表的长度作为插入位置。
data = [1, 2, 3]
data.insert(len(data), 4)
print (data)
>>> [1, 2, 3, 4]
5)列表算法 (5) List arithmetic)
What happens when you add two or more lists? Suppose you have the following two lists.
添加两个或多个列表会怎样? 假设您有以下两个列表。
list_A = [1, 2, 3, 4, 5]
list_B = [6, 7, 8, 9, 10]
If you add them, you would expect an element-wise addition of the two lists. However, you will get a single list with the elements of both the lists appended (concatenated) in the order of addition.
如果添加它们,则可能期望将两个列表逐个元素地添加。 但是,您将获得一个列表,其中两个列表的元素均按添加顺序附加(连接)。
list_A + list_B
>>> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The order is important. For lists, A + B is not equal to B + A. So, if you reverse the order of addition, you will get a different result.
顺序很重要。 对于列表,A + B不等于B +A。 因此,如果您颠倒加法顺序,则会得到不同的结果。
list_B + list_A
>>> [6, 7, 8, 9, 10, 1, 2, 3, 4, 5]
您可以减去,相乘或除以两个列表吗? (Can you subtract, multiply, or divide two lists?)
No, you can’t. For example, if you try to subtract the above two lists, you will get a TypeError. Similarly, an error will be thrown for multiplication or division. Try it out to convince yourself.
不,你不能。 例如,如果您尝试将上述两个列表相减,则会得到TypeError 。 同样,将为乘法或除法抛出错误。 尝试说服自己。
If you multiply the list by a positive integer greater than 0, your list will be repeated (replicated) that many times. For example, multiplying a list by 3 repeats the list 3 times. Multiplication by a float number (3.0) yields an error. Multiplying the list by either 0 or a negative integer yields an empty list.
如果将列表乘以大于0的正整数,则列表将重复(复制)多次。 例如,将列表乘以3会使列表重复3次。 乘以浮点数(3.0)会产生错误。 将列表乘以0或负整数将得到一个空列表 。
# Multiplication by positive integer
data = [1, 2, 3]
data * 3 # equivalent to data + data + data
>>> [1, 2, 3, 1, 2, 3, 1, 2, 3]# Multiplication by 0
data * 0
>>> []
Note: An error will be reported if you try to multiply by [3] instead of 3.
注意:如果您尝试乘以[3]而不是3,则会报告错误。
6)倒转清单 (6) Reversing a list)
There are two ways to reverse a list.
有两种方法可以反转列表。
a) Using slicing as [::-1]. This will not change the list in-place. You will have to re-assign the list to reflect the changes in the original list.
a)使用切片为[::-1]。 这不会就地更改列表。 您将不得不重新分配列表以反映原始列表中的更改。
data = [1, 2, 3]
data[::-1]
>>> [3, 2, 1]print (data)
>>> [1, 2, 3] # The original list does not change# You have to re-assign the list after reversing
data = [1, 2, 3]
data = data[::-1] # Re-assign print (data)
>>> [3, 2, 1]
b) Using the list.reverse() function. Here, you do not need to reassign as the list is reversed in-place.
b)使用list.reverse() 功能。 在此,您无需重新分配,因为该列表是就地反转的。
data = [1, 2, 3]
data.reverse() # reverses the list in-place print (data)
>>> [3, 2, 1] # The original list does not change
7)对列表进行排序 (7) Sorting a list)
There are two direct ways to sort a list.
有两种直接的方法可以对列表进行排序。
a) Using the sorted() function. This will not sort the list in-place.b) Using thelist.sort() function. This performs in-place sorting.
a)使用sorted() 功能。 这不会就地对列表进行排序。b)使用list.sort() 功能。 这将执行就地排序。
In both the functions, you can choose to sort in ascending or descending order by using the keyword “reverse”. If “reverse=True”, the list is sorted in descending order. By default, the list is sorted in ascending order.
在这两个功能中,都可以使用关键字“ reverse”选择以升序还是降序排序。 如果“ reverse = True”,则列表按降序排序。 默认情况下,列表按升序排序。
# First method using sorted()
data = [7, 4, 1, 3, 8, 5, 9, 6, 2]
sorted(data, reverse=False) # Same as sorted(data) due to default
>>> [1, 2, 3, 4, 5, 6, 7, 8, 9]############################################################## Second method using list.sort()
data = [7, 4, 1, 3, 8, 5, 9, 6, 2]
data.sort(reverse=True)
print (data)
>>> [1, 2, 3, 4, 5, 6, 7, 8, 9]
字符串如何排序? (How are the strings sorted?)
- Strings of different lengths will be sorted alphabetically by default. 默认情况下,不同长度的字符串将按字母顺序排序。
- If strings have the same starting alphabet but in different cases, the uppercase gets preference. 如果字符串的起始字母相同,但情况不同,则大写优先。
-
If two or more strings have the same case first letter, they will be sorted alphabetically based on the second letter and so on.
如果两个或多个字符串的首字母大小写相同,则将根据第二个字母按字母顺序对它们进行排序 等等。
Let us look at some string examples using the second method.
让我们看看使用第二种方法的一些字符串示例。
data = ['pineapple', 'kiwi', 'apple', 'azure', 'Apricot', 'mango']
data.sort() # in-place sorting
print (data)
>>> ['Apricot', 'apple', 'azure', 'kiwi', 'mango', 'pineapple']#############################################################data = ['pineapple', 'kiwi', 'apple', 'Apricot', 'mango']
data.sort(reverse=True)
print (data)
>>> ['pineapple', 'mango', 'kiwi', 'apple', 'Apricot']
如何根据字符串的长度排序? (How to sort the strings based on their lengths?)
You need to use the keyword key=len. If you want a descending order of lengths, use an additional keyword reverse=True.
您需要使用关键字key=len 。 如果要按长度降序排列,请使用其他关键字reverse=True 。
data = ['pineapple', 'kiwi', 'apple', 'Apricot', 'orange', 'mango']
data.sort(key=len, reverse=True)
print (data)
>>> ['pineapple', 'Apricot', 'orange', 'apple', 'mango', 'kiwi']
8)项目索引 (8) Index of an item)
If you want to get the index of an item in a given list, you can do so using the command list.index(item). It searches for the item in the whole list. If the same item appears more than once, you will get only the index of its first occurrence.
如果要获取给定列表中某项的索引,可以使用命令list.index(item) 。 它在整个列表中搜索项目。 如果同一项目出现多次,您将仅获得其首次出现的索引。
grades = [70, 100, 97, 70, 85]
grades.index(100)
>>> 7grades.index(70) # 70 appears twice at indices 0 and 3
>>> 0 # Only the first index returns
Suppose your list is quite large and you want to search for an element only in a particular subset of the list. You can specify the “start” and the “end” index for the subset.
假设您的列表很大,并且您只想在列表的特定子集中搜索元素。 您可以为子集指定“开始”和“结束”索引。
grades = [70, 100, 97, 70, 85, 100, 400, 200, 32] # Search in the whole list
grades.index(100)
>>> 7# Search in the partial list from index 3 until index 8grades.index(100, 3, 8)
>>> 5 # Now the index of the second 100 is returned
9)计算清单中的项目频率 (9) Counting item frequency in a list)
You can count the frequency of a given item in a list using list.count(item). Let us consider the following example.
您可以使用list.count(item)列表中给定项目的频率。 让我们考虑以下示例。
data = [6, 4, 1, 4, 4, 3, 4, 8, 5, 4, 6, 2, 6]
data.count(4)
>>> 5
函数 count() 用法示例 (Example usage of the function count())
Suppose you want to count and print the frequency of all the elements. For this, we first need the unique items in the list. I will use NumPy’s unique().
假设您要计算并打印所有元素的频率。 为此,我们首先需要列表中的唯一项。 我将使用NumPy的unique() 。
import numpy as npdata = [1, 1, 4, 4, 3, 1, 3, 2, 4, 2]for item in np.unique(data):
print("{} occurs {} times in the list"\
.format(item, data.count(item)))>>> 1 occurs 3 times in the list
>>> 2 occurs 2 times in the list
>>> 3 occurs 2 times in the list
>>> 4 occurs 3 times in the list
10)清单理解 (10) List comprehensions)
Suppose you want to compute the cube of numbers from 0 to 5 and store them in a list. You first need to initialize an empty list, create a for loop, and then append the cubes of individual numbers to this list.
假设您要计算从0到5的数字立方体并将它们存储在列表中。 您首先需要初始化一个空列表,创建一个for循环,然后将各个数字的多维数据集附加到此列表中。
cubes = []
for i in range(6):
cubes.append(i**3)
print (cubes)
>>> [0, 1, 8, 27, 64, 125]
The above code is too much for such a simple task, right? Well, you can simply things using “List Comprehensions” as shown below.
对于这样一个简单的任务,上面的代码太多了,对吧? 好吧,您可以简单地使用“列表推导” 如下所示。
cubes = [i**3 for i in range(6)]
print (cubes)
>>> [0, 1, 8, 27, 64, 125]
11)复制清单 (11) Copying a list)
Suppose you have a list called ‘list_A’ and you assign this list to another list called ‘list_B’. If you delete an element from ‘list_A’, you would expect that ‘list_B’ will not change. The code below shows that this is not the case. Deleting an element from ‘list_A’ also removed it from ‘list_B’.
假设您有一个名为“ list_A”的列表,并将此列表分配给另一个名为“ list_B”的列表。 如果您从“ list_A”中删除一个元素,则希望“ list_B”不会更改。 下面的代码表明情况并非如此。 从“ list_A”中删除元素也会将其从“ list_B”中删除。
list_A = [1, 2, 3, 4, 5]
list_B = list_Adel list_A[0] # Delete an element from list_Aprint (list_A, list_B)
# [2, 3, 4, 5] [2, 3, 4, 5]
为什么list_B受到影响? (Why does list_B get affected?)
It is because when you write list_A = list_B, you create a reference to ‘list_A’. Hence, the changes in ‘list_A’ will also be reflected in ‘list_B’.
这是因为当您编写list_A = list_B ,会创建对“ list_A”的引用。 因此,“ list_A”中的更改也将得到反映 在“ list_B”中。
如何避免list_B发生变化? (How to avoid changes in list_B?)
The answer is to create a shallow copy. I will explain two ways to do it.
答案是创建浅表副本。 我将解释两种方法。
a) Using list.copy()b) Using list[:]
a)使用list.copy() b)使用list[:]
The following example shows that now deleting an element from ‘list_A’ does not affect the shallow copy i.e., the ‘list_B’.
以下示例显示,现在从“ list_A”中删除元素不会影响浅表副本,即“ list_B”。
# First method using list.copy()
list_A = [1, 2, 3, 4, 5]
list_B = list_A.copy()del list_A[0] # Delete an element from list_A
print (list_A, list_B)
# [2, 3, 4, 5] [1, 2, 3, 4, 5]#############################################################
# Second method using list[:]
list_A = [1, 2, 3, 4, 5]
list_B = list_A[:]del list_A[0] # Delete an element from list_A
print (list_A, list_B)
# [2, 3, 4, 5] [1, 2, 3, 4, 5]
12)嵌套列表 (12) Nested lists)
A list that contains another sublist as an element is called a nested list. The element sublist can contain further sublists. The elements inside the sublists can also be accessed using indexing and slicing. Let us consider the following example.
包含另一个子列表作为元素的列表称为嵌套列表 。 元素子列表可以包含其他子列表。 子列表中的元素也可以使用索引和切片进行访问。 让我们考虑以下示例。
data = [1, 2, 3, [4, 5, 6]]data[2] # Single element
>>> 3 data[3] # Sublist
>>> [4, 5, 6]
Now the question is, “How to access the elements of the sublist?”. You can access them using double indices. For example, data[3] returns the sublist. So the first element of this sublist can be accessed using data[3][0].
现在的问题是,“如何访问子列表的元素?”。 您可以使用双索引访问它们。 例如,data [3]返回子列表。 因此,可以使用data [3] [0]访问此子列表的第一个元素。
data[3][0]
>>> 4data[3][1]
>>> 5data[3][2]
>>> 6
Now consider the following list that has a sublist within the sublist. The length of the list is 4 where the first 3 elements are 1, 2, and 3, and the last element is [4, 5, 6, [7, 8, 9]]. The length of the last element, which is a sublist, is 4. This way, you keep going deeper and deeper into the nested lists.
现在考虑下面的列表,该列表在子列表中具有一个子列表 。 列表的长度为4,其中前三个元素为1、2和3,最后一个元素为[4、5、6,[7、8、9]]。 最后一个元素(即子列表)的长度为4。这样一来,您将越来越深入嵌套列表。
To access the elements of the sublists, you need to use double indices, triple indices, etc. as exemplified below.
要访问子列表的元素,您需要使用双索引,三索引等,如下所示。
data = [1, 2, 3, [4, 5, 6, [7, 8, 9]]] # A nested list# Length of the list
len(data)
>>> 4# The last element
data[3]
>>> [4, 5, 6, [7, 8, 9]]# Length of the last element
len(data[3])
>>> 4#############################################################
# Accessing the elements of the first sublist
data[3][1] # Double indices
>>> 5data[3][3] # Double indices
>>> [7, 8, 9]#############################################################
# Accessing the elements of the second sublist
data[3][3][0] # Triple indices
>>> 7data[3][3][-1] # Triple indices
>>> 9
This brings me to the end of this article. I covered a majority of operations related to lists and the reader is now expected to have gained improved familiarity with lists in Python. If you are interested in learning about the new features in the upcoming version 3.10 of Python and in Matplotlib 3.0, refer to the following posts.
这使我到本文的结尾。 我介绍了与列表有关的大多数操作,现在希望读者对Python中的列表有更好的了解。 如果您有兴趣了解即将发布的Python 3.10版本和Matplotlib 3.0中的新功能 ,请参阅以下文章。
翻译自: https://towardsdatascience.com/data-structures-in-python-da813beb2a0d
python中定义数据结构



所有评论(0)