【Python】Collection - list

Posted by 西维蜀黍 on 2019-11-01, Last Modified on 2024-05-02

List

In Python, square brackets ([]) indicate a list, and individual elements in the list are separated by commas.

The “empty list” is just an empty pair of brackets [ ]. The ‘+’ works to append two lists, so [1, 2] + [3, 4] yields [1, 2, 3, 4] (this is just like + with strings).

Here’s a simple example of a list that contains a few kinds of bicycles:

bicycles = ['trek', 'cannondale', 'redline', 'specialized'] 
print(bicycles)

list 的常用方法

  • list.remove(x) - 移除列表中第一个值为 x 的元素。如果没有这样的元素,则抛出 ValueError 异常。

  • list.pop([i]) - 删除列表中给定位置的元素并返回它。如果没有给定位置,a.pop() 将会删除并返回列表中的最后一个元素。( 方法签名中 i 两边的方括号表示这个参数是可选的,而不是要你输入方括号。你会在 Python 参考库中经常看到这种表示方法)。

  • list.clear() - 删除列表中所有的元素。相当于 del a[:]

  • list.index(x[, start[, end]]) - 返回列表中第一个值为 x 的元素的从零开始的索引。如果没有这样的元素将会抛出 ValueError 异常。可选参数 startend 是切片符号,用于将搜索限制为列表的特定子序列。返回的索引是相对于整个序列的开始计算的,而不是 start 参数。

  • list.count(x) - 返回元素 x 在列表中出现的次数。

  • list.sort(key=None, reverse=False) - 对列表中的元素进行排序(参数可用于自定义排序,解释请参见 sorted())。

  • list.reverse() - 反转列表中的元素。

  • list.copy() - 返回列表的一个浅拷贝。相当于 a[:]

列表方法示例:

>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4)  # Find next banana starting a position 4
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()
'pear'

你可能已经注意到,像 insertremove 或者 sort 方法,只修改列表,没有打印出返回值——它们返回默认值 None 。这是Python中所有可变数据结构的设计原则。

你可能会注意到的另一件事是并非所有数据或可以排序或比较。 例如,[None, 'hello', 10] 就不可排序,因为整数不能与字符串比较,而 None 不能与其他类型比较。 并且还存在一些没有定义顺序关系的类型。 例如,3+4j < 5+7j 就不是一个合法的比较。

初始化 list

>>> [0]*5
[0, 0, 0, 0, 0]

Oparations - Read

通过索引获取子元素

用索引来访问list中每一个位置的元素,记得索引是从0开始的:

>>> classmates[0]
'Michael'
>>> classmates[1]
'Bob'
>>> classmates[2]
'Tracy'
>>> classmates[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

当索引超出了范围时,Python会报一个IndexError错误,所以,要确保索引不要越界,记得最后一个元素的索引是len(classmates) - 1

如果要取最后一个元素,除了计算索引位置外,还可以用-1做索引,直接获取最后一个元素:

>>> classmates[-1]
'Tracy'

以此类推,可以获取倒数第2个、倒数第3个:

>>> classmates[-2]
'Bob'
>>> classmates[-3]
'Michael'
>>> classmates[-4]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

当然,倒数第4个就越界了。

也可以通过指定 index,倒着取元素:

>>> a
[1, 2, 3]
>>> n = 1
>>> a[~n]
2

循环 list

如果要对list实现类似Java那样的下标循环怎么办?Python内置的enumerate函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身:

>>> for i, value in enumerate(['A', 'B', 'C']):
...     print(i, value)
...
0 A
1 B
2 C

Oparations - Insertion

  • list.append(x) - 在列表的末尾添加一个元素。相当于 a[len(a):] = [x]

  • list.extend(iterable) - 使用可迭代对象中的所有元素来扩展列表。相当于 a[len(a):] = iterable

  • list.insert(i, x) - 在给定的位置插入一个元素。第一个参数是要插入的元素的索引,所以 a.insert(0, x) 插入列表头部, a.insert(len(a), x) 等同于 a.append(x)

>>> a = [1,2]
>>> a.extend([3,2])
>>> a
[1, 2, 3, 2]
>>> a.append(4)
>>> a.append([4,5])
>>> a
[1, 2, 3, 2, 4, [4, 5]]

list.append(elem) - Appending Elements to the End of a List

The simplest way to add a new element to a list is to append the item to the list.

Common error: does not return the new list, just modifies the original.

When you append an item to a list, the new element is added to the end of the list. Using the same list we had in the previous example, we’ll add the new element ‘ducati’ to the end of the list:

motorcycles = ['honda', 'yamaha', 'suzuki'] 
print(motorcycles)

motorcycles.append('ducati') 
print(motorcycles)

The append() method adds ‘ducati’ to the end of the list without affecting any of the other elements in the list:

['honda', 'yamaha', 'suzuki']
['honda', 'yamaha', 'suzuki', 'ducati']

list.insert(index, elem) - Inserting Elements into a List

You can add a new element at any position in your list by using the insert() method. You do this by specifying the index of the new element and the value of the new item.

motorcycles = ['honda', 'yamaha', 'suzuki'] 

motorcycles.insert(0, 'ducati')
print(motorcycles)

In this example, the code inserts the value ‘ducati’ at the beginning of the list. The insert() method opens a space at position 0 and stores the value ‘ducati’ at that location. This operation shifts every other value in the list one position to the right:

['ducati', 'honda', 'yamaha', 'suzuki']

list.extend(list2)

list.extend(list2) adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend().

Oparations - Concatenation

>>> [1, 2, 3] + [4, 5, 6] 				# Concatenation
[1, 2, 3, 4, 5, 6]

>>> ['Ni!'] * 4 
['Ni!', 'Ni!', 'Ni!', 'Ni!']			# Repetition

Oparations - Deletion

Removing Elements from a List

del - Removing an Item Using the del Statement

Often, you’ll want to remove an item or a set of items from a list. For example, when a player shoots down an alien from the sky, you’ll most likely want to remove it from the list of active aliens. Or when a user decides to cancel their account on a web application you created, you’ll want to remove that user from the list of active users. You can remove an item according to its position in the list or according to its value.

If you know the position of the item you want to remove from a list, you can use the del statement.

motorcycles = ['honda', 'yamaha', 'suzuki'] 
print(motorcycles)

del motorcycles[0] 
print(motorcycles)

The code uses del to remove the first item, ‘honda’, from the list of motorcycles:

['honda', 'yamaha', 'suzuki'] 
['yamaha', 'suzuki']

list.pop() - Removing an Item

Sometimes you’ll want to use the value of an item after you remove it from a list.

motorcycles = ['honda', 'yamaha', 'suzuki'] 
print(motorcycles)

popped_motorcycle = motorcycles.pop() 
print(motorcycles) 
print(popped_motorcycle)

The output shows that the value ‘suzuki’ was removed from the end of the list and is now stored in the variable popped_motorcycle:

['honda', 'yamaha', 'suzuki'] 
['honda', 'yamaha'] 
suzuki

list.pop(index)

Removes and returns the element at the given index. Returns the rightmost element if index is omitted (roughly the opposite of append()).

Oparations - Search

list.index(elem) - searches for the given element

Searches for the given element from the start of the - list and returns its index. Throws a ValueError if the element does not appear (use “in” to check without a ValueError).

list.remove(elem)

Searches for the first instance of the given element and removes it (throws ValueError if not present).

Checking Whether a Value Is Not in a List

Other times, it’s important to know if a value does not appear in a list. You can use the keyword not in this situation. For example, consider a list of users who are banned from commenting in a forum. You can check whether a user has been banned before allowing that person to submit a comment:

banned_users = ['andrew', 'carolina', 'david'] 
user = 'marie'

if user not in banned_users:
	print(user.title() + ", you can post a response if you wish.") #Marie, you can post a response if you wish.

The line reads quite clearly. If the value of user is not in the list banned_users, Python returns True and executes the indented line.

The user ‘marie’ is not in the list banned_users, so she sees a message inviting her to post a response:

Misc

# append list
>>> [1] + [2,3,]
[1, 2, 3]
>>> [1] + [2,3]
[1, 2, 3]

# sort
>>> sorted([1,2,4,3])
[1, 2, 3, 4]

Sort

cars = ['bmw', 'audi', 'toyota', 'subaru'] 
cars.sort()
print(cars)

The sort() method changes the order of the list perma-nently. The cars are now in alphabetical order, and we can never revert to the original order:

['audi', 'bmw', 'subaru', 'toyota']

You can also sort this list in reverse alphabetical order by passing the argument reverse=True to the sort() method. The following example sorts the list of cars in reverse alphabetical order:

cars = ['bmw', 'audi', 'toyota', 'subaru'] 
cars.sort(reverse=True) 
print(cars)

Again, the order of the list is permanently changed:

['toyota', 'subaru', 'bmw', 'audi']

Printing a List in Reverse Order

To reverse the original order of a list, you can use the reverse() method.

If we originally stored the list of cars in chronological order according to when we owned them, we could easily rearrange the list into reverse chronological order:

cars = ['bmw', 'audi', 'toyota', 'subaru'] 
print(cars)

cars.reverse() 
print(cars)

Notice that reverse() doesn’t sort backward alphabetically; it simply reverses the order of the list:

['bmw', 'audi', 'toyota', 'subaru'] 
['subaru', 'toyota', 'audi', 'bmw']

Simple Statistics with a List of Numbers

A few Python functions are specific to lists of numbers. For example, you can easily find the minimum, maximum, and sum of a list of numbers:

>>> digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

>>> min(digits) 
0

>>> max(digits) 
9

>>> sum(digits) 
45

Copying a List

Often, you’ll want to start with an existing list and make an entirely new list based on the first one. Let’s explore how copying a list works and examine one situation in which copying a list is useful.

To copy a list, you can make a slice that includes the entire original list by omitting the first index and the second index ([:]). This tells Python to make a slice that starts at the first item and ends with the last item, producing a copy of the entire list.

For example, imagine we have a list of our favorite foods and want to make a separate list of foods that a friend likes. This friend likes everything in our list so far, so we can create their list by copying ours:

my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]

print("My favorite foods are:") 
print(my_foods)

print("\nMy friend's favorite foods are:") 
print(friend_foods)
My favorite foods are:

['pizza', 'falafel', 'carrot cake']

My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake']

子 list 获取

>>> a = [0,1,2,3,4,5,6,7]
>>> a[:2]
[0, 1]
# 从索引为 -1的元素开始取数据,到 list 的末尾,而索引为 -1的元素就是 7
>>> a[-1:]
[7]
>>> a[-2:]
[6, 7]

# 当第二个数字为负数,表示截取到该位置时停止,索引为-2表示从末尾往头部数,第 2 个元素(索引从 1 开始)
# 索引从 -1 开始,-1、-2...
>>> a[:-2]
[0, 1, 2, 3, 4, 5]
>>> a[:-1]
[0, 1, 2, 3, 4, 5, 6]

Comprehensions

Python includes a more advanced operation known as a list comprehension expression, which turns out to be a powerful way to process structures like our matrix. Suppose, for instance, that we need to extract the second column of our sample matrix. It’s easy to grab rows by simple indexing because the matrix is stored by rows, but it’s almost as easy to get a column with a list comprehension:

>>> col2 = [row[1] for row in M] 	# Collect the items in column 2

>>> col2 
[2, 5, 8]

>>> M 														# The matrix is unchanged
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

>>> 3 in [1, 2, 3] 
True

>>> for x in [1, 2, 3]: 
... print(x, end=' ') 
...

1 2 3

List comprehensions derive from set notation; they are a way to build a new list by running an expression on each item in a sequence, one at a time, from left to right. List comprehensions are coded in square brackets (to tip you off to the fact that they make a list) and are composed of an expression and a looping construct that share a variable name (row, here). The preceding list comprehension means basically what it says: “Give me row[1] for each row in matrix M, in a new list.” The result is a new list containing column 2 of the matrix.

作为其他数据结构

list 作为栈使用

列表方法使得列表作为堆栈非常容易,最后一个插入,最先取出(“后进先出”)。要添加一个元素到堆栈的顶端,使用 append() 。要从堆栈顶部取出一个元素,使用 pop() ,不用指定索引。例如

>>> stack = [3, 4, 5]
# push
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
# pop (return and remove the first element)
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]

# get the last element
>>> stack[-1]
4

list 作为队列使用

列表也可以用作队列,其中先添加的元素被最先取出 (“先进先出”);然而列表用作这个目的相当低效。因为在列表的末尾添加和弹出元素非常快,但是在列表的开头插入或弹出元素却很慢 (因为所有的其他元素都必须移动一位)。

若要实现一个队列, collections.deque 被设计用于快速地从两端操作。例如

>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry")           # Terry arrives
>>> queue.append("Graham")          # Graham arrives
>>> queue.popleft()                 # The first to arrive now leaves
'Eric'
>>> queue.popleft()                 # The second to arrive now leaves
'John'
>>> queue                           # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])

Reference

  • Learning Python
  • Python Crash Course (2nd Edition) : A Hands-On, Project-Based Introduction to Programming