• 1
    数据输入输出
    • 任务
  • 2
    条件语句
    • 任务
  • 3
    for循环
    • 任务
  • 4
    字符串
    • 任务
  • 5
    while循环
    • 任务
  • 6
    列表
    • 任务
  • 7
    二维数组
    • 任务
  • 8
    字典
    • 任务
  • 9
    集合
    • 任务
  • 10
    函数与递归
    • 任务
  • к

课程 6. Lists

难度:

任务«从列表中间提取一个订阅项»

💻 Python
假设你正在帮助学校食堂的一位厨师。每天他都会记录每种菜品准备了多少份。一周结束时,你得到了一份列表,上面列出了从周一到周日每天烹制的汤的份数。你需要找出从周三到周五(含)共烹制了多少份汤,以了解这道菜在周中时段的受欢迎程度。

输入格式

周一准备的汤的份数
周二煮的汤的份数
……
周日煮的汤的份数

输出格式

从周三到周五(含)准备的汤的总份数

示例

输入

50
45
60
55
70
30
25

输出

185

提示

Lists in Python: a detailed guide

A list is an ordered and mutable collection that can contain elements of various types. The word "mutable" means that you can add, delete, or modify list items after creating it. Lists in Python are similar to arrays in other programming languages, but they provide much more flexibility and built-in functions.

A useful tip: Use lists when the order of the items is important to you and when you may need to change the contents of the collection while the program is running.

Creating a list

The list is created using square brackets [] or using the constructor function list().

# Empty list
my_list = []

# A list with multiple my_list elements
= [1, 2, 3, 4, 5]

# A list with elements of different types
my_list = [1, "hello", 3.14, True]

# Creating a list from another iterable object, for example, the string
char_list = list("Python")
print(char_list) # Output: ['P', 'y', 't', 'h', 'o', 'n']

User input of the list

There are several ways to get a list from a user.

# Method 1: Input via the eval() function
# **ATTENTION:** It is EXTREMELY UNSAFE to use eval() with user input.,
# because it allows you to execute any arbitrary code.
# Use this method only for educational purposes and never in real projects.
my_list = eval(input("Enter the list in the format [1, 2, 3]: "))
print(my_list) # Output: [1, 2, 3]

# Method 2: The safe and preferred method
# Enter numbers separated by a space
s = input("Enter numbers separated by a space: ") # The user enters: 1 2 3 4 5
numbers_list = s.split() # We get a list of strings: ['1', '2', '3', '4', '5']
# To work with them as numbers, they need to be converted:
int_list = [int(num) for num in numbers_list]
print(int_list) # Output: [1, 2, 3, 4, 5]

Adding items to the list

Python provides several methods for adding items to a list:

  • append(): adds one item to the very end of the list. This is the fastest addition operation.
  • insert(): inserts an element into the specified position (by index), shifting the remaining elements.
  • extend(): Extends the list by adding to the end all the items from another collection (for example, another list).
numbers = [1, 2, 3]

# Adding an element to the end
of numbers.append(4)
print(numbers) # Output: [1, 2, 3, 4]

# Inserting an element at position 1
numbers.insert(1, 10)
print(numbers) # Output: [1, 10, 2, 3, 4]

# Adding multiple items from another list
numbers.extend([5, 6, 7])
print(numbers) # Output: [1, 10, 2, 3, 4, 5, 6, 7]

A useful tip: You can also combine lists using the + operator, but this creates a completely new list, rather than modifying an existing one, unlike extend().

list1 = [1, 2]
list2 = [3, 4]
list3 = list1 + list2
print(list3) # Output: [1, 2, 3, 4]
print(list1) # Output: [1, 2] (remained unchanged)

Access to list items

The list items are available by index. Indexing starts with 0 for the first element. Negative indexing is also supported, where -1 is the last element.

my_list = [10, 20, 30, 40, 50]
# Access to the first element
of print(my_list[0]) # Output: 10

# Access to the last element
of print(my_list[-1]) # Output: 50

# Access to the element by index 2
print(my_list[2]) # Output: 30

Important: An attempt to access a non-existent index will cause an error IndexError. Always make sure that the index is within the length of the list.

Changing list items

You can easily change the list items by accessing them by index. This is one of the key differences between lists and strings, since strings in Python are immutable.

my_list = [10, 20, 30, 40, 50]
my_list[1] = 25 # Replace the element with index 1
print(my_list) # Output: [10, 25, 30, 40, 50]

Cross-sections of the list

Slices allow you to get parts of a list by creating a new list. Syntax: list[start:stop:step].

  • start: initial index (enabled). If omitted, the slice will start from the beginning of the list.
  • stop: end index (not included). If omitted, the slice will go to the end of the list.
  • step: step. If omitted, it is equal to 1.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Slice 2 to 5 index (elements with indexes 2, 3, 4, 5)
sublist = numbers[2:6]
print(sublist) # Output: [3, 4, 5, 6]

# Slice from the beginning to the 5th index
sublist = numbers[:6]
print(sublist) # Output: [1, 2, 3, 4, 5, 6]

# Slice from index 5 to the end
sublist = numbers[5:]
print(sublist) # Output: [6, 7, 8, 9]

# Every second element
sublist = numbers[::2]
print(sublist) # Output: [1, 3, 5, 7, 9]

# Creating a copy of the list in reverse order
sublist = numbers[::-1]
print(sublist) # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1]

A useful tip: A slice always creates a new list (a shallow copy). This is a convenient way to copy the list: new_list = old_list[:].

Iterating through the list items

The lists can be iterated through using the for loop.

numbers = [1, 2, 3, 4, 5]

# Method 1: Direct search (preferably if you don't need an index)
# This method is more readable and "Pythonic"
for number in numbers:
    print(number, end=" ")
# Output: 1 2 3 4 5

print() # for line wrapping

# Method 2: Index search (when the index itself is needed)
for i in range(len(numbers)):
    print(f"Index {i}, value {numbers[i]}")

# Method 3: The ideal option when you need both an index and a value
# Use the built-in enumerate() function
for i, number in enumerate(numbers):
print(f"Index {i}, value {number}")

Processing of several neighboring elements

It is very important to keep in mind the range of the range function if you want to take several elements in one iteration of the loop so as not to go beyond the list.

numbers = [12, 6, 2, 4, 9, 6, 10]
# Comparing the current element with the next one
for i in range(len(numbers) - 1): # Go to the penultimate element
if numbers[i] > numbers[i+1]:
print(numbers[i], end=" ")
# Output: 12 6 9

General rule: If you access numbers[i+k] in the loop, then the range of the loop should be range(len(numbers) - k). For example, to process triples of elements (i, i+1, i+2), the loop will be for i in range(len(numbers) - 2).

Beautiful list content output

numbers = [1, 2, 3, 4, 5]

# Method 1: Through a loop and the end parameter
for i in range(len(numbers)):
    print(numbers[i], end=" ")
# Output: 1 2 3 4 5

print() # for line wrapping

# Method 2: More elegant and modern
# Using the "*" operator (unpacking the list)
print(*numbers) # by default, the separator is a space
# Output: 1 2 3 4 5

# You can specify any other separator
print(*numbers, sep=", ")
# Output: 1, 2, 3, 4, 5
main.py
测试 1
测试 2
测试 3
测试 4
测试 5
测试 6
测试 7
测试 8
测试 9
测试 10
开发者解答
# Создаем список с количеством порций за неделю
# Считываем количество порций супа за каждый день недели
porc = []
for i in range(7):
    porc.append(int(input()))

# Считаем сумму порций со среды по пятницу (индексы 2, 3, 4)
porc_sum = porc[2] + porc[3] + porc[4]

# Выводим результат
print(porc_sum)

🎉 恭喜! 🎉

你出色地完成了任务!这是一个不小的挑战,但你找到了正确答案。你离编程大师又近了一步!继续保持,每一步都让你更强大。

AD

广告

red-snake blue-snake green-snake

正在运行代码...

AI助手

你好!我是你的编程助手。随时向我提问关于 Python 的问题——我可以解释函数、方法,并帮助你完成当前任务!