实验四报告: 熟悉Python字典、集合、字符串的使用

发布时间 2023-10-14 14:35:13作者: Smera1d0

实验目标

本实验的主要目标是熟悉Python中字典、集合、字符串的创建和操作,包括字典的创建、访问、修改和合并,集合的创建、访问以及各种集合运算,以及字符串的创建、格式化和常用操作。

实验要求

通过编写Python代码,验证以下要求:

  1. 熟悉Python字典的创建、访问、修改、合并。
  2. 熟悉Python集合的创建、访问、以及各种集合运算。
  3. 熟悉Python字符串的创建、格式化、常用操作。

实验内容

1. Python字典的操作

首先,我们将研究Python字典的创建、访问、修改和合并。

字典的创建

# 创建一个字典
my_dict = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

字典的访问

# 访问字典中的值
name = my_dict["name"]
age = my_dict["age"]
print(f"Name: {name}, Age: {age}")

字典的修改

# 修改字典中的值
my_dict["age"] = 31
print(f"Updated Age: {my_dict['age']}")

字典的合并

# 合并两个字典
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged_dict = {**dict1, **dict2}
print("Merged Dictionary:", merged_dict)
#键和值合并为字典
keys = ['a','b','c']
values = [1,2,3]
merged_dict = dict(zip(keys, values))
print("Merged Dictionary:", merged_dict)

2. Python集合的操作

接下来,我们将研究Python集合的创建、访问以及各种集合运算。

集合的创建

# 创建一个集合
my_set = {1, 2, 3, 4, 5}

集合运算

# 集合运算示例
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}

# 并集
union_set = set1.union(set2)
print("Union Set:", union_set)
print("Union Set:", set1 | set2)

# 交集
intersection_set = set1.intersection(set2)
print("Intersection Set:", intersection_set)
print("Intersection Set:", set1 & set2)

# 差集
difference_set = set1.difference(set2)
print("Difference Set:", difference_set)
print("Difference Set:", set1 - set2)

3. Python字符串的操作

最后,我们将研究Python字符串的创建、格式化和常用操作。

字符串的创建

# 创建一个字符串
my_string = "Hello, World!"

字符串的格式化

以下是三种常见的字符串格式化方式:%d%c%s

  1. %d:用于整数格式化

    • %d 用于插入整数值到字符串中。例如,您可以将整数变量插入到字符串中以生成动态文本。

    示例:

    age = 30
    message = "My age is %d years old." % age
    print(message)
    

    输出:

    My age is 30 years old.
    
  2. %c:用于字符格式化

    • %c 用于插入单个字符到字符串中。这通常与字符变量一起使用。

    示例:

    initial = 'A'
    message = "My name starts with the letter %c." % initial
    print(message)
    

    输出:

    My name starts with the letter A.
    
  3. %s:用于字符串格式化

    • %s 用于插入字符串到字符串中。这是一种通用的字符串插值方式,可以用于字符串以及其他数据类型的格式化。

    示例:

    name = "Alice"
    greeting = "Hello, %s!" % name
    print(greeting)
    

    输出:

    Hello, Alice!
    

Python 3.6及更高版本还支持更现代的f-strings,它们提供了更简洁和直观的方式来格式化字符串,但上述的%d%c%s 仍然是常见且有效的方式。

# 字符串格式化
name = "Alice"
age = 25
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)

常用字符串操作

# 常用字符串操作
original_string = "This is a sample string."

# 字符串长度
length = len(original_string)
print("String Length:", length)

# 字符串分割
split_string = original_string.split(" ")
print("Split String:", split_string)

# 字符串替换
new_string = original_string.replace("sample", "modified")
print("Replaced String:", new_string)

结论

通过本实验,我们成功熟悉了Python字典、集合和字符串的创建和操作。这些基本概念和技能在Python编程中非常重要,将有助于我们更好地处理数据和文本处理任务。