Python Crash Course study notes - Chapter 4: WORKING WITH LISTS

Traverse the list

For use to traverse.

$ cat months.py
months=['jan','feb','march']
# 注意,months后的冒号(:)是必需的
for month in months:
# print之前必须缩进
        print(month)

Special attention must be spaces or print statement before <tab>the key can not write head, otherwise an error:

$ python3 months.py
  File "months.py", line 3
    print(m.title())
        ^
IndentationError: expected an indented block

Results are as follows:

$ python3 months.py
jan
feb
march

Furthermore:

$ cat months.py
months=['jan','feb','march']
for month in months:
        print(f"the current month is {month.title()}.")

$ python3 months.py
the current month is Jan.
the current month is Feb.
the current month is March.

Statement after the for loop, if the band indentation, it will repeat execution, if the top row of the first to write (no indentation), perform only once.

$ cat months.py
months=['jan','feb','march']
for month in months:
        print(f"the current month is {month.title()}.")
        print('in loop')
print('not in loop')

$ python3 months.py
the current month is Jan.
in loop
the current month is Feb.
in loop
the current month is March.
in loop
not in loop

The following code runtime error:

$ cat months.py
months=['jan','feb','march']
for month in months:
        print(f"the current month is {month.title()}.")
print('not in loop')
        print('in loop')

$ python3 months.py
  File "months.py", line 5
    print('in loop')
    ^
IndentationError: unexpected indent

Avoid indentation (identification) error

Python uses indentation interpretation of whether the relevant lines of code to make the code easier to read.
statement after the for loop has at least one line must be indented. If you need a multi-row cycle, these rows indent. This is the C language {and }is similar to the code block.

Also being given unnecessary indent:

>>> a=1
>>>     print(a)
  File "<stdin>", line 1
    print(a)
    ^
IndentationError: unexpected indent

In the for loop, unnecessary indentation will cause logic errors.
Finally, for the last loop of the colon ( :) is required.

List of numbers

Use range function.

>>> for i in range(1,5):
...     print(i)
...
1
2
3
4

The range function can also specify step value (step size):

>>> for i in range(1, 11, 2):
...     print(i)
...
1
3
5
7
9

Note 5 and will not be printed, because it means stop at 5.

Since the function return value is, therefore range assignment list can be used to:

>>> numbers=range(1,5)
>>> print(numbers)
[1, 2, 3, 4]

The following functions print square meter, which **represents the square, another initialization list is empty the first line is necessary:

$ cat squares.py
squares = []
for value in range(1, 11):
     squares.append(value ** 2)
print(squares)

$ python squares.py
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Part of the statistical functions:

>>> nums = [ 1, 2, 3, 4 ]
>>> min(nums)
1
>>> max(nums)
4
>>> sum(nums)
10
>>> sum(nums)/len(nums)
2.5

List ComprehensionsThe for loop and List assignments into one statement:

>>> squares = [value*10 for value in range(1, 11)]
>>> print(squares)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

And part of the work of the List

slice

Part of the list, two parameters represent the start to the end to:

>>> seasons = ['spring', 'summer', 'autumn', 'winter']
>>> print(seasons[1:2])
['summer']
>>> print(seasons[2:4])
['autumn', 'winter']
# 如果第一个参数省略,则开始于第一个成员
>>> print(seasons[:4])
['spring', 'summer', 'autumn', 'winter']
# 如果最后一个参数省略,则结束于最后一个成员
>>> print(seasons[0:])
['spring', 'summer', 'autumn', 'winter']
>>> print(seasons[-3:])
['summer', 'autumn', 'winter']

List portion may also be used for loop:

>>> for s in seasons[0:]:
...     print(s)
...
spring
summer
autumn
winter

copy

First look at an example of a failure:

>>> seasons_copy=seasons
>>> print(seasons_copy)
['spring', 'summer', 'autumn', 'winter']
>>> seasons[0]='SPRING'
>>> print(seasons_copy)
['SPRING', 'summer', 'autumn', 'winter']

You can see, this is not a copy, two variables are pointing to the same List.

The following is the correct approach:

>>> seasons = ['spring', 'summer', 'autumn', 'winter']
>>> seasons_copy = seasons[:]
>>> seasons[0]='SPRING'
>>> print(seasons_copy)
['spring', 'summer', 'autumn', 'winter']

Tuple (tuple)

Immutable (immutable) of List called Tuple.
Tuple is not the
member of the List is included in the []definition. The members of the Tuple (comma ,) division:

d=1,2,3,4

However, in order beautiful, it can also be used ()to surround, if only one member, it ()is necessary:


>>> d=(1,2,3,4)
>>> d=(1,)
>>>> d[0]=5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

Tuple and List traversal like this does not repeat.
Tuple the members can not be modified, but said Tuple variables can be modified, that is, you can point to the new Tuple.

Code style

code is read more often than it is written

The following recommendations from the Enhancement Proposal Python ( PEP ).
Use 4 spaces instead of <tab>as an indenting
each line of code do not exceed 80 characters
per line comments do not exceed 72 characters
using blank lines to enhance code readability

Published 352 original articles · won praise 42 · views 550 000 +

Guess you like

Origin blog.csdn.net/stevensxiao/article/details/103979609