Elysia Tools

在一个清晰的工作台里浏览工具、案例、可视化和主题指南。

热门分类

专题

语言
ZHDERUPTENFRES

Elysia Tools

导航

编程语言

Python 代码样本:输出、数据结构与文件操作

选择 Python 代码片段检查输出、列表变化和文件读写。

案例

这个案例集合中的条目

代码python简单

Python Hello World

Python Hello World程序和基本语法示例

难度

2/10

预计时间

10 min

标签

python, programming, beginner

前置条件

Basic programming concepts

python
# Python Hello World Examples

# 1. Basic Hello World
print("Hello, World!")

# 2. Hello World with variable
message = "Hello, World!"
print(message)

# 3. Hello World with function
def say_hello():
    return "Hello, World!"

print(say_hello())

# 4. Hello World with function parameters
def greet(name):
    return f"Hello, {name}!"

print(greet("World"))
print(greet("Python"))

# 5. Hello World with class
class Greeter:
    def __init__(self, message="Hello, World!"):
        self.message = message
    
    def greet(self):
        return self.message

greeter = Greeter()
print(greeter.greet())

# 6. Hello World with user input
name = input("Enter your name: ")
print(f"Hello, {name}!")

# 7. Hello World multiple times
for i in range(5):
    print(f"Hello, World! {i + 1}")

# 8. Hello World with list
hellos = ["Hello", "Bonjour", "Hola", "Ciao", "こんにちは"]
for greeting in hellos:
    print(f"{greeting}, World!")

# 9. Hello World with dictionary
greetings = {
    "en": "Hello",
    "es": "Hola", 
    "fr": "Bonjour",
    "de": "Hallo",
    "ja": "こんにちは"
}

for lang, greeting in greetings.items():
    print(f"{greeting}, World! ({lang})")

# 10. Hello World with file I/O
with open("hello.txt", "w") as f:
    f.write("Hello, World!")

with open("hello.txt", "r") as f:
    content = f.read()
    print(f"From file: {content}")

# Basic data types examples
integer = 42
float_num = 3.14
string = "Python"
is_boolean = True
list_data = [1, 2, 3, 4, 5]
tuple_data = (1, 2, 3)
dictionary = {"name": "Python", "version": 3.9}

print(f"Integer: {integer}, Type: {type(integer)}")
print(f"Float: {float_num}, Type: {type(float_num)}")
print(f"String: {string}, Type: {type(string)}")
print(f"Boolean: {is_boolean}, Type: {type(is_boolean)}")
print(f"List: {list_data}, Type: {type(list_data)}")
print(f"Tuple: {tuple_data}, Type: {type(tuple_data)}")
print(f"Dictionary: {dictionary}, Type: {type(dictionary)}")

# Control flow examples
age = 18
if age >= 18:
    print("You are an adult")
else:
    print("You are a minor")

# Loop examples
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(f"I like {fruit}")

# While loop example
count = 0
while count < 3:
    print(f"Count: {count}")
    count += 1

# List comprehensions
squares = [x**2 for x in range(10)]
print(f"Squares: {squares}")

# Exception handling
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
finally:
    print("This always runs")
代码python中等

Python 数据结构

Python数据结构和操作的综合示例

难度

5/10

预计时间

20 min

标签

python, data structures, programming

前置条件

Basic Python syntax

python
# Python Data Structures Examples

# 1. Lists (Mutable sequences)
# Creating lists
fruits = ["apple", "banana", "cherry"]
numbers = list(range(1, 6))  # [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]

# List operations
fruits.append("orange")           # Add to end
fruits.insert(1, "grape")        # Insert at index
fruits.remove("banana")          # Remove first occurrence
popped = fruits.pop()            # Remove and return last item
fruits[0] = "kiwi"               # Update item

# List slicing
print(fruits[1:3])      # Items from index 1 to 2
print(fruits[:2])       # Items from start to index 1
print(fruits[2:])       # Items from index 2 to end

# List comprehensions
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]

# 2. Tuples (Immutable sequences)
# Creating tuples
coordinates = (10, 20)
single_item = (42,)      # Note the comma
empty_tuple = ()

# Tuple operations
x, y = coordinates      # Unpacking
print(f"X: {x}, Y: {y}")

# Named tuples
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p1 = Point(10, 20)
print(f"Point: ({p1.x}, {p1.y})")

# 3. Dictionaries (Key-value pairs)
# Creating dictionaries
student = {
    "name": "Alice",
    "age": 20,
    "grades": [85, 90, 78]
}

# Dictionary operations
student["major"] = "Computer Science"    # Add key-value pair
age = student.get("age", 0)              # Get with default
del student["grades"]                    # Delete key-value pair

# Dictionary methods
keys = student.keys()
values = student.values()
items = student.items()

# Dictionary comprehensions
squares_dict = {x: x**2 for x in range(6)}
print(f"Squares dictionary: {squares_dict}")

# 4. Sets (Unique elements)
# Creating sets
unique_numbers = {1, 2, 3, 2, 1}  # {1, 2, 3}
from_set = set([1, 2, 3, 2, 1])

# Set operations
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}

print(f"Union: {set_a | set_b}")           # {1, 2, 3, 4, 5, 6}
print(f"Intersection: {set_a & set_b}")    # {3, 4}
print(f"Difference: {set_a - set_b}")      # {1, 2}
print(f"Symmetric difference: {set_a ^ set_b}")  # {1, 2, 5, 6}

# 5. Strings (Immutable sequences)
text = "Hello, Python!"
print(f"Length: {len(text)}")
print(f"Upper: {text.upper()}")
print(f"Lower: {text.lower()}")
print(f"Replace: {text.replace('Python', 'World')}")

# String methods
words = text.split(", ")
print(f"Words: {words}")
joined = "-".join(words)
print(f"Joined: {joined}")

# 6. Stack and Queue using lists
# Stack (LIFO)
stack = []
stack.append(1)    # push
stack.append(2)
stack.append(3)
top_item = stack.pop()  # pop

# Queue (FIFO) - using collections.deque
from collections import deque
queue = deque()
queue.append(1)    # enqueue
queue.append(2)
queue.append(3)
front_item = queue.popleft()  # dequeue

# 7. Nested data structures
# List of dictionaries
students = [
    {"name": "Alice", "age": 20, "grades": [85, 90, 78]},
    {"name": "Bob", "age": 22, "grades": [92, 88, 95]},
    {"name": "Charlie", "age": 21, "grades": [78, 85, 82]}
]

# Accessing nested data
for student in students:
    avg_grade = sum(student["grades"]) / len(student["grades"])
    print(f"{student['name']}: Average grade = {avg_grade:.1f}")

# 8. Advanced list operations
# Sorting
numbers = [64, 34, 25, 12, 22, 11, 90]
numbers.sort()                    # In-place sort
sorted_numbers = sorted(numbers, reverse=True)  # New sorted list

# Sorting with custom key
students.sort(key=lambda x: x["age"])

# 9. Dictionary with complex keys
complex_dict = {
    (1, 2): "Point at (1,2)",
    "nested": {"inner": "value"},
    frozenset([1, 2, 3]): "Immutable set as key"
}

# 10. Performance comparison
import time

# List vs Set for membership testing
large_list = list(range(100000))
large_set = set(large_list)

# Test list membership
start = time.time()
result = 99999 in large_list
list_time = time.time() - start

# Test set membership
start = time.time()
result = 99999 in large_set
set_time = time.time() - start

print(f"List membership time: {list_time:.6f}s")
print(f"Set membership time: {set_time:.6f}s")
代码python中等

Python 文件处理

Python文件I/O操作和文件系统操作

难度

6/10

预计时间

25 min

标签

python, file operations, i/o

前置条件

Basic Python syntax

python
# Python File Handling Examples

import os
import json
import csv
from pathlib import Path

# 1. Basic file operations
# Write to file
with open("example.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("This is a file handling example.\n")
    file.write("Python makes file operations easy.\n")

# Read from file
with open("example.txt", "r") as file:
    content = file.read()
    print("File content:")
    print(content)

# Read line by line
with open("example.txt", "r") as file:
    print("\nReading line by line:")
    for line_num, line in enumerate(file, 1):
        print(f"Line {line_num}: {line.strip()}")

# 2. Different file modes
# Append mode
with open("example.txt", "a") as file:
    file.write("\nAppended text at the end.")

# Read and write mode (r+)
with open("example.txt", "r+") as file:
    content = file.read()
    file.seek(0)  # Go to beginning
    file.write("MODIFIED: " + content)

# 3. Working with binary files
# Write binary data
data = bytes(range(256))  # 0-255 bytes
with open("binary.bin", "wb") as file:
    file.write(data)

# Read binary data
with open("binary.bin", "rb") as file:
    binary_data = file.read()
    print(f"\nBinary data length: {len(binary_data)} bytes")

# 4. JSON file operations
data_to_save = {
    "name": "John Doe",
    "age": 30,
    "skills": ["Python", "JavaScript", "SQL"],
    "address": {
        "street": "123 Main St",
        "city": "New York"
    }
}

# Write JSON to file
with open("data.json", "w") as file:
    json.dump(data_to_save, file, indent=2)

# Read JSON from file
with open("data.json", "r") as file:
    loaded_data = json.load(file)
    print("\nLoaded JSON data:")
    print(json.dumps(loaded_data, indent=2))

# 5. CSV file operations
# Write CSV
with open("students.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Age", "Grade"])
    writer.writerow(["Alice", 20, "A"])
    writer.writerow(["Bob", 22, "B"])
    writer.writerow(["Charlie", 21, "A+"])

# Read CSV
with open("students.csv", "r") as file:
    reader = csv.reader(file)
    print("\nCSV content:")
    for row in reader:
        print(row)

# 6. Using pathlib for file operations
from pathlib import Path

# Create a directory structure
data_dir = Path("data")
data_dir.mkdir(exist_ok=True)

# Create and write to file using pathlib
sample_file = data_dir / "sample.txt"
sample_file.write_text("Hello from pathlib!")

# Read file using pathlib
content = sample_file.read_text()
print(f"\nPathlib content: {content}")

# File operations with pathlib
if sample_file.exists():
    print(f"File size: {sample_file.stat().st_size} bytes")
    print(f"File path: {sample_file.absolute()}")

# 7. Context manager for custom file operations
class FileManager:
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode
        self.file = None
    
    def __enter__(self):
        self.file = open(self.filename, self.mode)
        return self.file
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.file:
            self.file.close()

# Using custom context manager
with FileManager("custom.txt", "w") as file:
    file.write("Custom context manager example!")

# 8. Working with temporary files
import tempfile

# Create temporary file
with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file:
    temp_file.write("This is temporary data")
    temp_path = temp_file.name

print(f"\nTemporary file created at: {temp_path}")

# Read temporary file
with open(temp_path, 'r') as file:
    print(f"Temp file content: {file.read()}")

# Clean up (delete=False means we need to delete manually)
os.unlink(temp_path)

# 9. File system operations
# Get current working directory
current_dir = os.getcwd()
print(f"\nCurrent directory: {current_dir}")

# List files in directory
print("Files in current directory:")
for item in os.listdir("."):
    if os.path.isfile(item):
        print(f"  File: {item}")
    elif os.path.isdir(item):
        print(f"  Directory: {item}/")

# Create directory
new_dir = "test_directory"
if not os.path.exists(new_dir):
    os.makedirs(new_dir)
    print(f"Created directory: {new_dir}")

# Remove directory
os.rmdir(new_dir)
print(f"Removed directory: {new_dir}")

# 10. Error handling in file operations
try:
    with open("nonexistent.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("\nFile not found error handled gracefully")

try:
    with open("/protected/file.txt", "w") as file:
        file.write("test")
except PermissionError:
    print("Permission error handled gracefully")

# Clean up created files
files_to_remove = ["example.txt", "binary.bin", "data.json", "students.csv", "custom.txt", "sample.txt"]
for file_path in files_to_remove:
    try:
        os.remove(file_path)
    except FileNotFoundError:
        pass

# Remove data directory
try:
    import shutil
    shutil.rmtree("data")
except FileNotFoundError:
    pass

print("\nFile handling examples completed!")

工具

经常与该案例搭配使用的工具

相关内容

相关案例集合

相关内容

相关专题

工具使用指南

帮助搜索与理解工作流的案例说明

概览

从最小输出开始,再检查可变列表的操作顺序;文件示例会写入磁盘,适合在隔离目录中练习。

选择代码卡片

卡片提供代码展示和复制;选择需要的片段放到自己的 Python 环境。整张卡片包含多个独立示例,不一定适合作为一个无交互脚本运行。

三个样本的文本已通过语法解析;语法正确不意味着所有输入、路径或运行环境都满足。

选择代码卡片
样本卡片适合检查
Python Hello World基础打印和函数
Python 数据结构列表与其他数据结构
Python 文件处理文件、JSON 和 CSV 读写

运行前检查环境

Hello World 卡片还包含 input,完整运行会等待输入。文件操作卡片使用相对路径并包含写入、追加与修改操作。

只复制正在验证的片段;文件练习放在临时工作目录,确认写入目标和权限。

使用方式

  1. 1复制目标代码片段。
  2. 2确认 Python 版本、输入和工作目录。
  3. 3运行后比较输出或文件内容。

常见失败与 edge cases

  • 完整脚本

    后续片段可能等待输入、依赖文件或产生其他副作用。

  • 文本编码

    真实文件编码和路径应按目标环境明确配置。

示例

1. 核对最小输出

如何使用

从第一张卡片复制第一条 print 语句,在 Python 中运行。

结果

控制台输出 Hello, World!,不需要运行后续交互代码。

2. 追踪列表变化

如何使用

从第二张卡片复制 fruits 定义至 fruits[0] 赋值的语句,然后打印 fruits。

结果

结果为 ["kiwi", "grape", "cherry"];append 后的 orange 被 pop 移除。

3. 查看文件模式

如何使用

在第三张卡片找到以 w 打开 example.txt 的代码,在隔离目录运行该片段。

结果

example.txt 包含三行文本;w 模式会覆盖已存在的同名文件。

专题

药代动力学教学模型与结果核查

用于教学或 QA 的药代公式、模型假设和结果一致性核查,不提供用药剂量、诊断或临床建议。

专题

经典与现代密码工具

在安全的教学或 CTF 场景中比较可逆的经典变换与现代加密,并明确玩具密码不等于安全防护。

专题

文本前后缀与包裹符号批处理,整行整词一次到位

给文本行或词批量添加前后缀,为 SQL、配置和 Markdown 给每个值加引号或反引号包裹,并剥掉粘贴列表带来的编号、符号和装饰。

专题

数学与数字转换工作流

按清晰的精度检查流程转换计量单位、进制、分数、科学计数法、罗马数字以及字节/位数值。

首页
工具3212
案例593
可视化471
文件查看器103
专题239
标签333
图像、音频与视频657

图像、音频、视频处理、转换与优化工具

数学、日期与金融647

计算器、数值计算、日期逻辑、统计与金融工具

设计与颜色298

颜色、版式、图形、视觉样式与设计辅助工具

文本与写作209

写作、清洗、格式化、提取与文本分析工具

开发与 Web193

开发者工具、网络处理、Web 调试与自动化辅助工具

转换与编码175

格式、文件、压缩包、单位与编码转换工具

潜客测验发布与联系人交接
讣告、悼词与纪念卡的家属复核及交付
本地习惯记录的备份、恢复演练与分享前检查
长文改编 X 串文与 LinkedIn 帖子的事实复核与交付
Markdown 互动课件审校、离线演示与交付

© 2026 Elysia Tools. 保留所有权利。

文档价格关于我们服务条款隐私政策Cookie 政策联系我们

Data Processing

AI数据规范化器

AI驱动的数据格式规范化工具,使用高级AI分析智能清理和标准化混乱数据

AI

AI Token 预估器

按语言体系分析文本,并预估 OpenAI、Codex、Claude 和 DeepSeek 的 token 消耗

Data Processing

CSV过滤器

按列值过滤CSV数据,支持多个条件和运算符。支持12种过滤运算符,包括等于、包含、大于、小于和空值检查。 额外过滤器示例: [{"column": "年龄", "operator": "greater_than", "value": "25"}] [{"column": "状态", "operator": "equals", "value": "激活"}, {"column": "分数", "operator": "greater_equal", "value": "80"}] [{"column": "姓名", "operator": "contains", "value": "张"}, {"column": "邮箱", "operator": "is_not_empty"}]

Security

CSV/JSON 数据水印器

为 CSV 或 JSON 导出注入可见或签名式水印字段,以便后续追踪共享数据

Data Processing

CSV 转数据库迁移规划器

根据 CSV 数据推断关系型 schema,并为 PostgreSQL、MySQL、SQLite 或 SQL Server 生成建表和 ALTER 迁移计划

Format Conversion

CSV转JSON转换器

将CSV数据转换为JSON格式,支持自定义解析选项

Data Processing

CSV转换器

转换和处理CSV数据,支持列操作、计算和数据类型转换。 操作示例: • 重命名列: [{"type": "rename", "column": "旧列名", "new_name": "新列名"}] • 添加计算列: [{"type": "add_column", "new_column": "总计", "formula": "价格 * 数量"}] • 删除列: [{"type": "remove_column", "remove_column": "要删除的列名"}] • 转换数据类型: [{"type": "convert_type", "convert_column": "年龄", "target_type": "number"}] • 计算值: [{"type": "calculate", "target_column": "总计", "expression": "价格 * 税率 + 运费"}] • 过滤行: [{"type": "filter_values", "filter_column": "状态", "operator": "equals", "value": "激活"}]

Data Processing

数据规范化器

基于代码逻辑的数据格式规范化工具,使用程序化方法清理和标准化混乱数据

数据

CSV示例

各种数据类型、大小和复杂度级别的CSV示例文件

文档文件

PDF示例

2026-02-01 到 2026-02-10 工具生成的PDF示例

媒体

二维码示例

用于测试二维码读取和生成工具的示例二维码图像

可观测性

分布式追踪示例

使用 Jaeger、OpenTelemetry 和其他现代可观测性工具的综合分布式追踪示例,适用于微服务架构

DevOps

ELK Stack 日志分析示例

全面的 ELK Stack(Elasticsearch、Logstash、Kibana)示例,用于分布式系统中的日志聚合、处理和可视化

云服务

AWS EventBridge 示例

AWS EventBridge 示例,包括事件总线、规则、目标、模式注册表、自定义事件和跨账户事件路由,适用于无服务器事件驱动架构