|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
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'}
求解,感觉看了资料也不会,求详解
问题要求我们从给定的字典 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() 函数将集合转换为列表。
|
|