Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Вкладений Цикл While | Вкладені Цикли
Посібник з циклів Python

book
Вкладений Цикл While

У реальному житті вам може знадобитися організувати або аналізувати дані з кількома рівнями, наприклад, відстеження витрат на різні поїздки. Вкладений цикл while дозволяє ефективно обробляти ці багатовимірні сценарії, коли кількість ітерацій не визначена заздалегідь.

Уявіть, що у вас є кілька поїздок, і кожна поїздка має список витрат (перельоти, готелі, їжа тощо). Використовуючи вкладений цикл while, ви можете обчислити загальну вартість для кожної поїздки.

# List of trips with their respective expenses
travel_costs = [
[500, 200, 100, 150], # Trip 1: Flights, Hotels, Food, Activities
[600, 250, 120, 200], # Trip 2: Flights, Hotels, Food, Activities
[550, 180, 130, 170] # Trip 3: Flights, Hotels, Food, Activities
]

# Initialize the outer loop to iterate over trips
i = 0
while i < len(travel_costs):
total_cost = 0 # Reset the total cost for the current trip
j = 0
# Inner loop to iterate over expenses in each trip
while j < len(travel_costs[i]):
total_cost += travel_costs[i][j] # Add the expense to the total cost
j += 1
# Print the total cost for the current trip
print(f"Total cost for Trip {i + 1}: ${total_cost}")
i += 1 # Move to the next trip
123456789101112131415161718192021
# List of trips with their respective expenses travel_costs = [ [500, 200, 100, 150], # Trip 1: Flights, Hotels, Food, Activities [600, 250, 120, 200], # Trip 2: Flights, Hotels, Food, Activities [550, 180, 130, 170] # Trip 3: Flights, Hotels, Food, Activities ] # Initialize the outer loop to iterate over trips i = 0 while i < len(travel_costs): total_cost = 0 # Reset the total cost for the current trip j = 0 # Inner loop to iterate over expenses in each trip while j < len(travel_costs[i]): total_cost += travel_costs[i][j] # Add the expense to the total cost j += 1 # Print the total cost for the current trip print(f"Total cost for Trip {i + 1}: ${total_cost}") i += 1 # Move to the next trip
copy
  1. Зовнішній цикл: while i < len(travel_costs) ітерується через список поїздок, де кожен рядок представляє витрати на одну поїздку;
  2. Внутрішній цикл: while j < len(travel_costs[i]) ітерується через витрати на поточну поїздку, підсумовуючи їх у змінній total_cost;
  3. Виведення результатів: після підсумовування витрат на поїздку програма виводить загальну вартість для цієї поїздки;
  4. Перехід до наступної поїздки: збільшуйте i, щоб проаналізувати наступну поїздку, поки всі поїздки не будуть оброблені;
  5. Кінцевий результат: після завершення циклу виведіть номер поїздки з найвищою загальною вартістю та її значення.
Завдання

Swipe to start coding

Ви аналізуєте набір даних про витрати на подорожі, де кожен підсписок представляє витрати на одну поїздку. Кожна поїздка включає різні витрати, такі як перельоти, готелі, їжа та активності. Оскільки витрати варіюються, вам потрібно визначити найбільшу витрату для кожної поїздки, щоб відстежувати основні витрати.

  1. Вам надано список travel_costs, де кожен підсписок представляє витрати на одну поїздку.
  2. Для кожної поїздки визначте найбільшу витрату.
  3. Збережіть найбільші витрати у списку max_costs.

Рішення

# List of travel costs (each sublist represents a trip)
travel_costs = [
[5, 15, 10, 8, 25, 30, 55, 68, 75, 5],
[60, 20, 60, 70, 80, 80, 80, 90, 90, 90],
[100, 100, 100, 100, 50, 110, 110, 120, 120, 120, 130],
[130, 140, 39, 140, 150, 150, 150, 150, 160, 160],
[170, 180, 180, 190, 40, 190, 200],
[200, 200, 200, 210, 11, 220, 220, 220, 250, 250, 250],
[280, 300, 300, 110, 300, 320, 350, 400, 400, 450],
[480, 500, 500, 90, 500, 550, 600, 700]
]

# List to store maximum costs per trip
max_costs = []

# Iterate through trips using while loop
i = 0
while i < len(travel_costs):
j = 0
max_cost = travel_costs[i][0]

while j < len(travel_costs[i]):
if travel_costs[i][j] > max_cost:
max_cost = travel_costs[i][j]
j += 1

max_costs.append(max_cost)
i += 1

# Testing
print("Maximum Travel Costs:", max_costs)
Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 2
# List of travel costs (each sublist represents a trip)
travel_costs = [
[5, 15, 10, 8, 25, 30, 55, 68, 75, 5],
[60, 20, 60, 70, 80, 80, 80, 90, 90, 90],
[100, 100, 100, 100, 50, 110, 110, 120, 120, 120, 130],
[130, 140, 39, 140, 150, 150, 150, 150, 160, 160],
[170, 180, 180, 190, 40, 190, 200],
[200, 200, 200, 210, 11, 220, 220, 220, 250, 250, 250],
[280, 300, 300, 110, 300, 320, 350, 400, 400, 450],
[480, 500, 500, 90, 500, 550, 600, 700]
]

# List to store maximum costs per trip
max_costs = []



# Testing
print("Maximum Travel Costs:", max_costs)
toggle bottom row
some-alt