如何在 Python 中创建包含数字范围的列表

PythonPythonBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

Python 列表是一种通用的数据结构,能够存储包括数字在内的各种元素。在本教程中,你将学习如何在 Python 中创建包含一定范围数字的列表,这在各种编程任务中是一项实用的技术。我们将探讨生成包含数字序列的列表的方法,并讨论如何在你的 Python 程序中有效地应用这些范围列表。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/ControlFlowGroup -.-> python/for_loops("For Loops") python/ControlFlowGroup -.-> python/list_comprehensions("List Comprehensions") python/DataStructuresGroup -.-> python/lists("Lists") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/for_loops -.-> lab-398166{{"如何在 Python 中创建包含数字范围的列表"}} python/list_comprehensions -.-> lab-398166{{"如何在 Python 中创建包含数字范围的列表"}} python/lists -.-> lab-398166{{"如何在 Python 中创建包含数字范围的列表"}} python/function_definition -.-> lab-398166{{"如何在 Python 中创建包含数字范围的列表"}} python/build_in_functions -.-> lab-398166{{"如何在 Python 中创建包含数字范围的列表"}} python/data_collections -.-> lab-398166{{"如何在 Python 中创建包含数字范围的列表"}} end

创建和理解 Python 列表

Python 列表是最常用的数据结构之一,它允许你在一个变量中存储多个项目。在深入探讨如何创建包含一定范围数字的列表之前,让我们先了解一下 Python 列表的基础知识。

首先,我们创建一个新的 Python 文件来进行操作。在 WebIDE 中:

  1. 点击顶部的 “File” 菜单
  2. 选择 “New File”
  3. 将文件命名为 python_lists.py
  4. 将其保存到 /home/labex/project 目录下

现在,让我们编写一些代码来了解 Python 列表的工作原理:

## Basic list creation
numbers = [1, 2, 3, 4, 5]
print("Basic list:", numbers)

## Lists can contain different data types
mixed_list = [1, "hello", 3.14, True]
print("Mixed data types:", mixed_list)

## Accessing list elements (indexing starts at 0)
print("First element:", numbers[0])
print("Last element:", numbers[4])

## Getting the length of a list
print("List length:", len(numbers))

## Modifying list elements
numbers[2] = 30
print("Modified list:", numbers)

## Adding elements to a list
numbers.append(6)
print("After append:", numbers)

## Removing elements from a list
numbers.remove(30)
print("After remove:", numbers)

让我们运行这个脚本以查看输出。在终端中:

  1. 确保你位于 /home/labex/project 目录下
  2. 运行以下命令:
python3 python_lists.py

你应该会看到以下输出:

Basic list: [1, 2, 3, 4, 5]
Mixed data types: [1, 'hello', 3.14, True]
First element: 1
Last element: 5
List length: 5
Modified list: [1, 2, 30, 4, 5]
After append: [1, 2, 30, 4, 5, 6]
After remove: [1, 2, 4, 5, 6]

如你所见,Python 列表有几个重要的特性:

  • 列表是有序集合,这意味着其中的项目有明确的顺序
  • 列表是可变的,允许你在创建后更改、添加或删除项目
  • 列表可以包含不同数据类型的项目
  • 列表中的每个元素都可以通过其索引(位置)来访问

既然我们已经了解了 Python 列表的基础知识,接下来就可以开始创建包含一定范围数字的列表了。

使用 range() 函数创建列表

Python 中的 range() 函数是一个内置函数,用于生成一系列数字。它通常与 list() 函数一起使用,以创建包含一定范围数字的列表。

让我们创建一个新的 Python 文件来探索 range() 函数:

  1. 点击顶部的 “File” 菜单
  2. 选择 “New File”
  3. 将文件命名为 range_lists.py
  4. 将其保存到 /home/labex/project 目录下

现在,让我们添加代码来探索 range() 函数的不同用法:

## Basic usage of range() function
## Note: range() returns a range object, not a list directly
## We convert it to a list to see all values at once

## range(stop) - generates numbers from 0 to stop-1
numbers1 = list(range(5))
print("range(5):", numbers1)

## range(start, stop) - generates numbers from start to stop-1
numbers2 = list(range(2, 8))
print("range(2, 8):", numbers2)

## range(start, stop, step) - generates numbers from start to stop-1 with step
numbers3 = list(range(1, 10, 2))
print("range(1, 10, 2):", numbers3)

## Creating a list of descending numbers
numbers4 = list(range(10, 0, -1))
print("range(10, 0, -1):", numbers4)

## Creating even numbers from 2 to 10
even_numbers = list(range(2, 11, 2))
print("Even numbers:", even_numbers)

## Creating odd numbers from 1 to 9
odd_numbers = list(range(1, 10, 2))
print("Odd numbers:", odd_numbers)

让我们运行这个脚本以查看结果:

python3 range_lists.py

你应该会看到以下输出:

range(5): [0, 1, 2, 3, 4]
range(2, 8): [2, 3, 4, 5, 6, 7]
range(1, 10, 2): [1, 3, 5, 7, 9]
range(10, 0, -1): [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Even numbers: [2, 4, 6, 8, 10]
Odd numbers: [1, 3, 5, 7, 9]

range() 函数有三种不同的用法:

  1. range(stop):生成从 0 到 stop - 1 的数字
  2. range(start, stop):生成从 startstop - 1 的数字
  3. range(start, stop, step):生成从 startstop - 1 的数字,每次递增 step

通过理解这些不同的形式,你可以创建各种类型的数字序列:

  • 顺序数字(递增计数)
  • 递减数字(递减计数)
  • 偶数
  • 奇数
  • 具有自定义间隔的数字

请记住,range() 函数本身返回一个 range 对象,这是一种节省内存的方式。我们使用 list() 函数将其转换为列表,以便一次性查看所有值或对其执行列表操作。

结合 range() 使用列表推导式

Python 提供了一个强大的特性,叫做列表推导式(list comprehensions),它能让你以简洁易读的方式创建列表。当与 range() 函数结合使用时,列表推导式为创建具有特定模式的列表提供了一种优雅的解决方案。

让我们创建一个新的 Python 文件来探索列表推导式:

  1. 点击顶部的 “File” 菜单
  2. 选择 “New File”
  3. 将文件命名为 list_comprehensions.py
  4. 将其保存到 /home/labex/project 目录下

现在,让我们添加代码来探索列表推导式与 range() 结合的工作方式:

## Basic list comprehension with range
## Format: [expression for item in iterable]
squares = [x**2 for x in range(1, 6)]
print("Squares of numbers 1-5:", squares)

## List comprehension with condition
## Format: [expression for item in iterable if condition]
even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print("Squares of even numbers 1-10:", even_squares)

## Creating a list of numbers divisible by 3
divisible_by_3 = [x for x in range(1, 31) if x % 3 == 0]
print("Numbers divisible by 3 (1-30):", divisible_by_3)

## Converting Celsius temperatures to Fahrenheit
celsius_temps = list(range(0, 101, 20))
fahrenheit_temps = [(c * 9/5) + 32 for c in celsius_temps]

print("Celsius temperatures:", celsius_temps)
print("Fahrenheit temperatures:", [round(f, 1) for f in fahrenheit_temps])

## Creating a list of tuples (number, square)
number_pairs = [(x, x**2) for x in range(1, 6)]
print("Numbers with their squares:")
for num, square in number_pairs:
    print(f"Number: {num}, Square: {square}")

让我们运行这个脚本以查看结果:

python3 list_comprehensions.py

你应该会看到以下输出:

Squares of numbers 1-5: [1, 4, 9, 16, 25]
Squares of even numbers 1-10: [4, 16, 36, 64, 100]
Numbers divisible by 3 (1-30): [3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
Celsius temperatures: [0, 20, 40, 60, 80, 100]
Fahrenheit temperatures: [32.0, 68.0, 104.0, 140.0, 176.0, 212.0]
Numbers with their squares:
Number: 1, Square: 1
Number: 2, Square: 4
Number: 3, Square: 9
Number: 4, Square: 16
Number: 5, Square: 25

列表推导式拥有简洁的语法,能让你用一行代码创建列表。其通用语法如下:

[expression for item in iterable if condition]

其中:

  • expression 是你想包含在新列表中的内容
  • item 是可迭代对象中的每个元素
  • iterable 是你要遍历的序列(如 range()
  • if condition 是可选的,用于筛选要包含的元素

与使用传统的 for 循环和 append() 方法创建列表相比,列表推导式更易读,而且通常效率更高。当与 range() 函数结合使用时,它们在创建具有特定模式或经过特定转换的数字列表时特别有用。

范围列表的实际应用

既然我们已经学习了如何使用范围创建列表,那么让我们来探索一些实际应用。这些示例将展示如何使用范围列表来解决常见的编程问题。

让我们为实际示例创建一个新的 Python 文件:

  1. 点击顶部的 “File” 菜单
  2. 选择 “New File”
  3. 将文件命名为 range_applications.py
  4. 将其保存到 /home/labex/project 目录下

现在,让我们为几个实际应用添加代码:

## Example 1: Sum of numbers from 1 to 100
total = sum(range(1, 101))
print(f"Sum of numbers from 1 to 100: {total}")

## Example 2: Creating a multiplication table
def print_multiplication_table(n):
    print(f"\nMultiplication table for {n}:")
    for i in range(1, 11):
        result = n * i
        print(f"{n} × {i} = {result}")

print_multiplication_table(7)

## Example 3: Generating a calendar of years
current_year = 2023
years = list(range(current_year - 5, current_year + 6))
print(f"\nYears (5 past to 5 future): {years}")

## Example 4: Creating a countdown timer
def countdown(seconds):
    print("\nCountdown:")
    for i in range(seconds, 0, -1):
        print(i, end=" ")
    print("Blast off!")

countdown(10)

## Example 5: Calculating factorial
def factorial(n):
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result

num = 5
print(f"\nFactorial of {num}: {factorial(num)}")

## Example 6: Creating a simple number guessing game
import random

def number_guessing_game():
    ## Generate a random number between 1 and 100
    secret_number = random.randint(1, 100)
    attempts = list(range(1, 11))  ## Maximum 10 attempts

    print("\nNumber Guessing Game")
    print("I'm thinking of a number between 1 and 100.")
    print("You have 10 attempts to guess it.")

    for attempt in attempts:
        ## In a real game, we would get user input
        ## For demonstration, we'll just print the logic
        print(f"\nAttempt {attempt}")
        print(f"(If this were interactive, you would guess a number here)")
        print(f"The secret number is: {secret_number}")

        ## Break after the first attempt for demonstration purposes
        break

number_guessing_game()

让我们运行这个脚本以查看结果:

python3 range_applications.py

你应该会看到展示每个实际应用的输出:

  1. 1 到 100 所有数字的总和
  2. 数字 7 的乘法表
  3. 一个年份列表(过去 5 年到未来 5 年)
  4. 从 10 到 1 的倒计时
  5. 5 的阶乘
  6. 数字猜谜游戏的工作原理演示

这些示例展示了如何将范围与列表结合使用,以高效地解决各种编程问题。在你的程序中使用范围列表的一些主要优点包括:

  1. 简化遍历数字序列的代码
  2. 高效的内存使用(范围对象不会在内存中存储所有数字)
  3. 轻松创建数字模式和序列
  4. 方便地与其他 Python 函数(如 sum()min()max())集成

通过掌握范围列表的创建和操作,你可以为各种应用编写更简洁、高效的 Python 代码。

总结

在本次实验中,你学习了如何在 Python 中创建和使用包含数字范围的列表。以下是你所掌握内容的回顾:

  1. 你学习了 Python 列表的基础知识,包括如何创建、访问和修改列表
  2. 你探索了 range() 函数以及如何使用它来生成数字序列
  3. 你了解了如何使用列表推导式基于范围创建更复杂的列表
  4. 你应用这些技术解决了实际的编程问题

这些技能对于许多 Python 编程任务来说是基础,从简单的数据处理到更复杂的算法。能够快速生成和操作数字序列是一个强大的工具,它将帮助你编写更高效、更有效的 Python 代码。

在你继续 Python 学习之旅时,你会发现这些技术在许多场景中都很有用,包括数据分析、Web 开发、科学计算等等。列表和 range() 函数的结合为在 Python 中处理数值数据提供了坚实的基础。