Pythonのクラッシュコースの研究ノート - 第4章:WORKING WITHリスト

リストをトラバース

トラバースに使用します。

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

特別な注意は、スペースやprint文の前になければなりません<tab>:鍵は書込みヘッド、それ以外の場合はエラーすることはできません

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

結果は以下の通りであります:

$ python3 months.py
jan
feb
march

さらに:

$ 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.

文は、forループ、バンドインデント場合、それが繰り返される実行後、書き込み(NOくぼみ)に第一のトップ行は、一度だけ実行する場合。

$ 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

次のコードの実行時エラー:

$ 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

避けインデント(識別)エラー

Pythonは読みのコードを容易にするために、コードのかどうか、関連する行のインデントの解釈を使用しています。
forループの後のステートメントには、少なくとも1行がインデントされている必要があります。あなたは複数行のサイクルが必要な場合は、これらの行はインデント。これは、C言語である{}コードブロックと同様です。

また、不要なインデントを与えられています:

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

forループでは、不要なインデントは論理エラーが発生します。
最後に、コロンの最後のforループ(:)が必要です。

数字のリスト

レンジ機能を使用してください。

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

範囲関数は、ステップ値(ステップサイズ)を指定することができます。

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

注5と、それは5でストップを意味するので、印刷されません。

関数の戻り値であるので、従って範囲割り当てリストをするために使用することができます。

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

以下の機能は、平方メートル、印刷**正方形を表すが、他の初期化リストは、最初の行が必要で空です。

$ 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]

統計関数の一部:

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

List Comprehensions1文にループし、リストの割り当てのために:

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

そして、リストの作品の一部

スライス

リストの一部は、2つのパラメータはに開始から終了までを表します。

>>> 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']

リスト部は、ループのために使用することができます。

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

コピー

失敗の例ではまず見て:

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

あなたが見ることができ、これはコピーではない、二つの変数が同じリストを指しています。

以下は、正しいアプローチです。

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

タプル(タプル)

リストの不変(不変)はタプルと呼ばれます。
タプルはない
に含まれているリストのメンバー[]定義。タプル(コンマのメンバー,)分割:

d=1,2,3,4

しかし、順序美しいで、それはまた使用することができます()唯一のメンバーは、それがあれば、サラウンドに()必要です。


>>> 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

このようなタプルとリストトラバーサルは繰り返されません。
タプルのメンバーが変更されますが、タプル変数であることを、あなたは新しいタプルを指すことができ、変更することができるとすることはできません。

コードスタイル

コードはより頻繁にそれが書かれているよりも、読まれます

拡張提案はPython(から次の推奨PEP)。
4つのスペースの代わりに使用してください<tab>インデントとして
超えてはなりませんコードの各行80文字
72文字超えていない行のコメントあたりの
コードの可読性を高めるために、空白行を使用して

公開された352元の記事 ウォン称賛42 ビュー550 000 +

おすすめ

転載: blog.csdn.net/stevensxiao/article/details/103979609