42

我正在努力解决 Python 中的一个小问题(我的程序现在是 3.2.3 版)。

我有一本看起来像这样的字典(这只是一个例子,实际上取自这里的另一篇文章):

[
    {"abc": "movies"},
    {"abc": "sports"},
    {"abc": "music"},
    {"xyz": "music"},
    {"pqr": "music"},
    {"pqr": "movies"},
    {"pqr": "sports"},
    {"pqr": "news"},
    {"pqr": "sports"},
]

我想简单地 print() 一个唯一值列表,消除重复项。在此列表的末尾,我想打印字典中唯一值的数量:

movies
sports
music
news

4

任何帮助表示赞赏。我发现这里还有一些其他的帖子有些相关,但我对 Python 的了解还不够,无法将其应用于这个特定问题。

4

4 回答 4

56

在这里使用set,因为它们只包含独特的项目。

>>> lis = [{"abc":"movies"}, {"abc": "sports"}, {"abc": "music"}, {"xyz": "music"}, {"pqr":"music"}, {"pqr":"movies"},{"pqr":"sports"}, {"pqr":"news"}, {"pqr":"sports"}]
>>> s = set( val for dic in lis for val in dic.values())
>>> s 
set(['movies', 'news', 'music', 'sports'])

循环这个集合以获得预期的输出:

for x in s:                                
    print x
print len(s)   #print the length of set after the for-loop
... 
movies
news
music
sports
4

这一行s = set( val for dic in lis for val in dic.values())大致相当于:

s = set()
for dic in lis:
   for val in dic.values():
      s.add(val)
于 2013-06-20T15:48:55.803 回答
25

You can exploit the properties of set for this purpose; each element is unique and duplicates will be ignored.

uniqueValues = set(myDict.values())

By using set in this way, duplicate elements returned from .values() will be discarded. You can then print them as follows:

for value in uniqueValues:  
    print(value)  
print(len(uniqueValues))
于 2017-02-18T23:33:35.633 回答
11

使用set()

from itertools import chain

unique_values = set(chain.from_iterable(d.values() for d in dictionaries_list))
for value in unique_values:
    print(value)

print(len(unique_values))

在 Python 2 上使用.itervalues()可以提高效率。因为你有一个字典列表,我们需要首先从每个字典中提取值;我itertools.chain.from_iterable()与生成器表达式一起使用以列出序列中的所有值:

>>> for value in set(chain.from_iterable(d.values() for d in dictionaries_list)):
...     print(value)
... 
news
sports
movies
music

另一种方法是在生成器表达式中使用嵌套循环:

>>> for value in set(v for d in dictionaries_list for v in d.values()):
...     print(value)
... 
news
sports
movies
music
于 2013-06-20T15:48:34.910 回答
7
dict = {'511':'Vishnu','512':'Vishnu','513':'Ram','514':'Ram','515':'sita'}
list =[] # create empty list
for val in dict.values(): 
  if val in list: 
    continue 
  else:
    list.append(val)

print list
于 2016-05-28T06:13:12.190 回答