Whalefall126 发表于 2023-8-13 23:21:25

direction list

Given the following dictionary, q19_d , write a Python program to identify all unique values in it and append the value to a list called output19. For example, given:

{112:'dog', 113:'cat', 119:'dog'}
the list of unique values would be:

['dog', 'cat']
Guaranteeing uniqueness
The most Pythonic approach to ensuring values are unique is to add them to a set. While the course material has not covered sets, you can (if you choose) get some additional insight from this this python.org tutorial.

q19_d = {112:'dog', 113:'cat', 119:'dog', 120:'dog', 126:'parrot', 130:'duck', 131:'dog', 133:'cat', 136:'duck', 139:'parrot'}

求解,感觉看了资料也不会,求详解

学习编程中的Ben 发表于 2023-8-13 23:21:57

识别并添加唯一值到列表

下面是一个Python程序,可以识别给定字典中的所有唯一值,并将这些值添加到名为output19的列表中:

q19_d = {112:'dog', 113:'cat', 119:'dog', 120:'dog', 126:'parrot', 130:'duck', 131:'dog', 133:'cat', 136:'duck', 139:'parrot'}
output19 = []

# 使用集合来保存唯一值
unique_values = set()

# 遍历字典的值
for value in q19_d.values():
    unique_values.add(value)

# 将唯一值添加到列表
output19 = list(unique_values)

print(output19)


输出:

['cat', 'dog', 'parrot', 'duck']


该程序首先创建了一个空的集合unique_values,然后遍历字典q19_d的值。在遍历过程中,每个值都会被添加到unique_values集合中,而集合会自动去除重复项。最后,将集合转换回列表output19,以满足问题要求。

希望这个解决方案对你有帮助!如果你有任何进一步的问题,请随时提问。

如果回答对你有帮助,请给我一个最佳答案!{:10_254:}{:10_254:}{:10_254:}

isdkz 发表于 2023-8-13 23:22:03

问题要求我们从给定的字典 q19_d 中找出所有的唯一值,并将这些值添加到一个名为 output19 的列表中。

解决这个问题的一种简洁的方法是使用集合(set)。集合是一种无序且不重复的数据结构,可以用来存储唯一的值。

我们可以通过遍历字典的值,并将它们添加到一个集合中来实现这个目标。最后,我们可以将集合转换为列表,得到我们想要的结果。

下面是解决这个问题的Python代码:

q19_d = {112:'dog', 113:'cat', 119:'dog', 120:'dog', 126:'parrot', 130:'duck', 131:'dog', 133:'cat', 136:'duck', 139:'parrot'}

output19 = list(set(q19_d.values()))

print(output19)


运行这段代码,将会输出 ['parrot', 'cat', 'dog', 'duck'] ,这是字典 q19_d 中所有唯一值的列表。

这个解决方案的关键是使用 set() 函数将字典的值转换为一个集合。由于集合中的元素是唯一的,所以我们可以确保最终得到的列表中的值也是唯一的。最后,我们使用 list() 函数将集合转换为列表。

ba21 发表于 2023-8-13 23:28:35

q19_d = {112:'dog', 113:'cat', 119:'dog', 120:'dog', 126:'parrot', 130:'duck', 131:'dog', 133:'cat', 136:'duck', 139:'parrot'}
pirnt(list(set(q19_d.values())))
q19_d.values() 取出值的集合
set 合并相同的值
list 转为列表
页: [1]
查看完整版本: direction list