简体   繁体   English

计算Python列表中的唯一值

[英]Count unique values in Python list

I have the following code I've been working on, but I can't seem to find a way to count the number of unique values in the anagram list. 我正在处理以下代码,但似乎找不到一种方法来计算字谜列表中唯一值的数量。 If I just print out: print len(anagram) I get the total value of the list, but it includes duplicates. 如果我只是打印出: print len(anagram)我得到列表的总值,但是它包括重复项。

I have tried to convert the list to a set and back to get rid of the duplicates, but have not had any luck. 我尝试将列表转换为集合,然后返回以消除重复项,但没有任何运气。

Thanks! 谢谢!

#import libraries 
import urllib, itertools

#import dictionary
scrabble = urllib.urlopen('http://www.puzzlers.org/pub/wordlists/ospd.txt').read().split()
#print the length of the dictionary
print len(scrabble)

#make anagrams from scrabble list
anagrams = [list(g) for k,g in itertools.groupby(sorted(scrabble, key=sorted), key=sorted)]


#print the largest anagram  
print "Largest number of anagrams for a word : ", len(max(anagrams, key=len)) 
print "Largest anagram word and values ", max(anagrams, key=len)

Use a set . 使用set set s hold only unique values: set s仅保留唯一值:

print len(set(anagram))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM