Seznamy

Introduction to Python for Developers

Jasmin Ludolf

Senior Data Science Content Developer

Problém

# Variables of ingredient names
ingredient_one = "pasta"
ingredient_two = "tomatoes"
ingredient_three = "garlic"
ingredient_four = "basil"
ingredient_five = "olive oil"
ingredient_six = "salt"
Introduction to Python for Developers

Seznamy jako záchrana!

  • Seznam = uložení více hodnot do jedné proměnné
    • Může obsahovat libovolnou kombinaci datových typů

 

# 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]
Introduction to Python for Developers

Zjištění datového typu

# Check the data type of a list
print(type(ingredients))
<class 'list'>
Introduction to Python for Developers

Přístup k prvkům seznamu

# Print all values in the list variable
print(ingredients)
['pasta', 'tomatoes', 'garlic', 'basil', 'olive oil', 'salt']
  • Seznamy jsou uspořádané a indexované
    • Python přiřazuje indexy od nuly pro první prvek
Introduction to Python for Developers

Přístup k prvkům seznamu

  • Seznam = []
  • Přístup k prvku = 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
Introduction to Python for Developers

Nalezení posledního prvku seznamu

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
Introduction to Python for Developers

Přístup k více prvkům

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]
  • K poslednímu indexu se přičítá jedničky, protože:
    • Python vrátí vše až po tento index, ale nezahrne ho
Introduction to Python for Developers

Přístup k více prvkům

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']
Introduction to Python for Developers

Střídavý přístup

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

# Access every second element print(ingredients[::2])
['pasta', 'garlic', 'olive oil']]
  • Vrátí prvky na indexech nula, dvě a čtyři
# Access every third element, starting at the second
print(ingredients[1::3])
['tomatoes', 'olive oil']
  • Vrátí prvky na indexech jedna a čtyři
Introduction to Python for Developers

Pojďme cvičit!

Introduction to Python for Developers

Preparing Video For Download...