0
0

More than 1 year has passed since last update.

Pythonの勉強

Last updated at Posted at 2022-12-31

目的

Pythonの知識を習得するため、わかりにくい点やノウハウなどを蓄積していく。

内容

辞書型とリスト型の使い分け

辞書型では、キーで検索できるため、キーに対応した値を出力できる。
一方、リスト型では、キーで検索できない。

#リスト型
l = [
    ['apple', 100],
    ['banana', 200],
    ['orange', 300],
]
#辞書型
fruits = {
    'apple': 100,
    'banana': 200,
    'orange': 300
}
print(fruits['apple'])
#出力結果
100

関数のdefault引数の注意点

default引数でリストを呼び出す際、1回目の呼び出しで、空のリストが返され、値が入る。
ただし、2回目の呼び出しでは、空のリストではなく、値の入ったリストが呼ばれ、値が追加される。

2回目で空のリストが返されないのは、引数lにリストの先頭のアドレスが入っているためである。
1回目の呼び出しで、リストの先頭アドレスに値が入り、
2回目の呼び出しで、先頭アドレスを指したまま(リストに値が入った状態)で、先頭の次のアドレスに値が入る。

def test_func(x, l=[]):
    l.append(x)
    return  l

r = test_func(100)
print(r)

r = test_func(100)
print(r)
#出力結果
[100]
[100, 100]

関数を呼び出す度に空のリストを返したい場合は、
以下のように、Noneとifを用いる。

def test_func(x, l=None):
    if l is None:
        l = []
    l.append(x)
    return  l

r = test_func(100)
print(r)

r = test_func(100)
print(r)
#出力結果
[100]
[100]
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0