dict #13
dict
#13
Replies: 5 comments 1 reply
-
移除列表中的重复项可以利用集合元素必须唯一的特性: my_list = [1, 2, 3, 4, 3, 2, 1]
seen = set()
unique_list = []
for item in my_list:
if item not in seen:
unique_list.append(item)
seen.add(item)
print(unique_list) |
Beta Was this translation helpful? Give feedback.
0 replies
-
查找字典中的最大值test_data = {'a': 10, 'b': 25, 'c': 5}
if not test_data: # 检查字典是否为空
print("字典为空")
max_key = None # 用于存储值最大的键
max_value = float('-inf') # 初始为负无穷,保证字典中的值大于它
for key, value in d.items(): # 遍历字典的键值对
if value > max_value: # 如果当前值大于 max_value,则更新
max_value = value
max_key = key
print(max_key) # 输出 'b' |
Beta Was this translation helpful? Give feedback.
0 replies
-
计算字典中所有值的总和sample_dict = {'a': 100, 'b': 200, 'c': 300}
total_sum = sum(sample_dict.values())
print("字典中值的总和为:", total_sum) |
Beta Was this translation helpful? Give feedback.
0 replies
-
打印集合的所有子集s = {1, 2, 3}
result = [set()];
for i in s:
new_sets = []
for j in result:
new_sets.append(j | {i})
result.extend(new_sets)
print(result) |
Beta Was this translation helpful? Give feedback.
0 replies
-
统计词频# 输入一段文章
text = input("请输入一段文章:")
# 将文章按空格分割成单词列表,并转换为小写以避免大小写差异
words = text.lower().split()
# 创建一个字典来统计每个单词的出现次数
word_count = {}
# 遍历每个单词,统计出现次数
for word in words:
# 如果单词已在字典中,计数加 1,否则添加到字典并初始化计数为 1
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 输出结果
print("每个单词的出现次数:")
for word, count in word_count.items():
print(f"{word}: {count}") |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
dict
循环语句是编程中的一个基本结构,它允许我们多次执行同一组指令,直到满足某个条件才结束。比如下面的这些应用场合,都非常适合使用循环:
https://py.qizhen.xyz/dict
Beta Was this translation helpful? Give feedback.
All reactions