Python learning road 3 - operation list

This series is a compilation of notes for the introductory book "Python Programming: From Getting Started to Practice", which belongs to the primary content. The title sequence follows the title of the book.
The content of this chapter is mainly about further operations on lists, as well as an initial understanding of the tuple data structure.

iterate over the list

This chapter is mainly about forloops:

# 代码:
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
    print(magician.title() + ", that was a great trick")
    print("I can't wait to see your next trick, " + magician.title() + ".\n")

print("Thank you, everyone. That was a great magic show!")

# 输出:
Alice, that was a great trick!
I can't wait to see your next trick, Alice.

David, that was a great trick!
I can't wait to see your next trick, David.

Carolina, that was a great trick!
I can't wait to see your next trick, Carolina.

Thank you, everyone. That was a great magic show!

There are two things worth noting here, one is the "colon": forthe line where the keyword is located has a colon at the end; the other is the indentation problem, the code blocks in Python are all indented as the standard, unlike C/C++, Languages ​​like Java represent blocks of code with curly braces. IndentationErrorRefers to indentation errors.

Create a list of values

This uses an important function that generates a sequence range(), and a list()function

# 代码:
print(list(range(6)))         # 结束值(不包含结束值)
print(list(range(1, 6)))      # 起始值(包含),结束值(不含)
print(list(range(1, 6, 2)))   # 起始值,结束值,步长;最后一个数小于结束值
print(list(range(6, 1, -1)))  # 负数步长,此时起始值要大于结束值
print(list(range(1, 6, -1)))  # 负数步长,若起始值小于结束值,则输出空列表

# 结果:
[0, 1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 3, 5]
[6, 5, 4, 3, 2]
[]

range()Functions are also often referred to as forloops, to identify the number of iterations, or to generate more complex lists:

# 代码:
squares = []
for value in range(1, 11):
    squares.append(value ** 2 + 1)
print(squares)

# 结果:
[2, 5, 10, 17, 26, 37, 50, 65, 82, 101]

For generating a list, there is also a more concise way of writing, that is, list comprehension. For example, the above code for generating a list can be shortened to one line:

# 代码:
squares = [value ** 2 for value in range(1, 11)]
print(squares)

squares_2 = [value ** 2 for value in range(1, 11) if value % 2 == 0]
print(squares_2)
# 结果:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[4, 16, 36, 64, 100]

List comprehensions can be more complex, so I won't repeat them here.

Perform simple statistical calculations on lists of numbers :
find the maximum, minimum, and sum of all elements of a list of numbers:

# 代码:
digits = list(range(10))
print(min(digits), max(digits), sum(digits))

# 结果:
0 9 45

use part of a list

slice

The slice operation is used to take part of the original list:

# 代码:
players = ['charles', 'martina', 'michael', 'florence', 'eli']
# [起始:结束:步长], 其中,结果列表包含起始索引,但不包含结束索引
print(players[0:3])
print(players[:3])   # 如果从0开始切片,0可以省略
print(players[1:3])
print(players[2:])   # 如果要便利到最后一个元素,结束索引可以省略,此时最后一个元素会被包含
print(players[-3:])  
print(players[::2])  # 设置了步长,但省略了结束索引,列表最后一个元素如果被遍历到,则会被包含
print(players[:4:2]) # 设置了步长和结束索引,索引4的元素也被遍历到了,但不会被包含在结果中

# 结果:
['charles', 'martina', 'michael']
['charles', 'martina', 'michael']
['martina', 'michael']
['michael', 'florence', 'eli']
['michael', 'florence', 'eli']
['charles', 'michael', 'eli']
['charles', 'michael']

The parameter setting of the slice operation is range()very similar to the parameter setting of the function. The start, end, and step size can be negative values. Here is a rule to summarize: if the step size is a positive number, the start position should be on the left side of the end position; If the step size is negative, the start position should be to the right of the end position.

copy list

There's the issue of deep and shallow duplication here. If you directly assign a variable to another variable, there is still only one copy of the data in the memory, not two copies. Both variables point to the same memory area in the memory where the data is stored. If you use the C/C++ language to Description, variables in Python are equivalent to pointers. These two variables (pointers) point to the same piece of memory. Operations on these two variables (pointers) will affect each other because they both act on the same memory block, as follows:

# 代码:
# 浅复制
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players)

names = players
names.append("test")
print(players)

# 结果:
['charles', 'martina', 'michael', 'florence', 'eli']
['charles', 'martina', 'michael', 'florence', 'eli', 'test']

If you want to copy the original data into a new one in memory, you need a deep copy, and the slicing operation is a way to achieve a deep copy:

# 代码:
# 深复制
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players)

names = players[:]
names.append("test")
print(names)
print(players)

# 结果:
['charles', 'martina', 'michael', 'florence', 'eli']
['charles', 'martina', 'michael', 'florence', 'eli', 'test']
['charles', 'martina', 'michael', 'florence', 'eli']

tuple

A data structure closely related to lists is the tuple. Lists are great for storing data sets that may change during program execution, and lists can be modified. However, sometimes you need to create a series of unmodifiable elements, in which case you need to use tuples.
Tuples are identified with parentheses. The following is to declare a tuple:

# 代码:
my_tuple = ()    # 空元组
one_tuple = (1,) # 声明含有一个元素的元组。不是one_tuple = (1)

Accessing elements in a tuple and traversing a tuple are the same as operations on a list; the difference is that the elements in a tuple cannot be changed.
Although the elements in the tuple cannot be changed, the value of the tuple variable can be changed. From the perspective of C/C++, a tuple variable is a pointer, and a tuple is equivalent to an constarray. Although the array cannot be changed, the pointer can point elsewhere.

# 代码:
test_tuple = (1, 2, 3, 4, 5)
print(test_tuple)
test_tuple = (2, 3, 4, 5, 6)
print(test_tuple)

# 结果:
(1, 2, 3, 4, 5)
(2, 3, 4, 5, 6)

Compared to lists, tuples are simpler data structures. A tuple is used when you need to store a set of values ​​that do not change over the lifetime of the program.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325658079&siteId=291194637