如果您有这样的集合列表:
listOstrings = ['cat in the hat','michael meyers','mercury.','austin powers','hi']
def StringLength(searchInteger, listOstrings):
'return Boolean value if the strings are shorter/longer than the first argument'
for i in listOstrings:
if len(i) < searchInteger:
print(False)
else:
print(True)
如何获得列表中唯一集合的数量?
我尝试过:
a_list = [{'a'}, {'a'}, {'a', 'b'}, {'a', 'b'}, {'a', 'c', 'b'}, {'a', 'c', 'b'}]
我遇到了错误:
TypeError:不可哈希类型:'set'
在这种情况下,所需的输出为:3,因为列表中有三个唯一的集合。
答案 0 :(得分:1)
您可以使用tuple
:
a_list = [{'a'}, {'a'}, {'a', 'b'}, {'a', 'b'}, {'a', 'c', 'b'}, {'a', 'c', 'b'}]
result = list(map(set, set(map(tuple, a_list))))
print(len(result))
输出:
[{'a', 'b'}, {'a'}, {'c', 'a', 'b'}]
3
一种不太实用的方法,也许更具可读性:
result = [set(c) for c in set([tuple(i) for i in a_list])]
答案 1 :(得分:1)
如何转换为元组?
a_list = [{'a'}, {'a'}, {'a', 'b'}, {'a', 'b'}, {'a', 'c', 'b'}, {'a', 'c', 'b'}]
print(len(set(map(tuple, a_list))))
输出:
3