リスト

開発者のためのPython入門

Jasmin Ludolf

Senior Data Science Content Developer

問題

# Variables of ingredient names
ingredient_one = "pasta"
ingredient_two = "tomatoes"
ingredient_three = "garlic"
ingredient_four = "basil"
ingredient_five = "olive oil"
ingredient_six = "salt"
開発者のためのPython入門

リストが助けになる!

  • リスト = 1つの変数に複数の値を格納する
    • データ型の任意の組み合わせを含むことができる
# List of ingredients
ingredients = ["pasta", "tomatoes", "garlic", "basil", "olive oil", "salt"]
# List of ingredients using variables as values
ingredients = [ingredient_one, ingredient_two, ingredient_three,
               ingredient_four, ingredient_five, ingredient_six]
開発者のためのPython入門

データ型を確認する

# Check the data type of a list
print(type(ingredients))
<class 'list'>
開発者のためのPython入門

リストの要素を取得する

# Print all values in the list variable
print(ingredients)
['pasta', 'tomatoes', 'garlic', 'basil', 'olive oil', 'salt']
  • リストは順序付けされ、番号が付けられている
    • Pythonは最初の要素に対して、ゼロから始まるインデックスを割り当てる
開発者のためのPython入門

リストの要素を取得する

  • リスト = []
  • 要素を取り出す= a_list[index]
ingredients = ["pasta", "tomatoes",
"garlic", "basil", "olive oil", "salt"]

# Get the value at the first index
print(ingredients[0])
pasta
# Get the fourth element
print(ingredients[3])
basil
開発者のためのPython入門

リストの最後の要素を取得する

ingredients = ["pasta", "tomatoes", "garlic", "basil", "olive oil", "salt"]

# Get the last element of a list
print(ingredients[5])
salt
# Get the last element of a list
print(ingredients[-1])
salt
開発者のためのPython入門

複数の要素を取り出す

ingredients = ["pasta", "tomatoes", "garlic", "basil", "olive oil", "salt"]

# Access the second and third elements
print(ingredients[1:3])
["tomatoes", "garlic"]
  • [first_element:last_element + 1]
  • 最後の要素のインデックスに 1 を加える理由:
    • Python は指定したインデックスまでのすべての要素を返すが、そのインデックス自体は含まない
開発者のためのPython入門

複数の要素を取り出す

ingredients = ["pasta", "tomatoes", "garlic", "basil", "olive oil", "salt"]

# Access all elements from the third index onwards
print(ingredients[3:])
['basil', 'olive oil', 'salt']
# Get the first three elements
print(ingredients[:3])
['pasta', 'tomatoes', 'garlic']
開発者のためのPython入門

1つおきに取り出す

ingredients = ["pasta", "tomatoes", "garlic", "basil", "olive oil", "salt"]

# Access every second element print(ingredients[::2])
['pasta', 'garlic', 'olive oil']]
  • インデックス0、2、4の項目を返す
# Access every third element, starting at the second
print(ingredients[1::3])
['tomatoes', 'olive oil']
  • インデックス1と4の項目を返す
開発者のためのPython入門

練習しましょう!

開発者のためのPython入門

Preparing Video For Download...