[英]How to check whether two tuples in the list of lists are not same
lt1 = [(1, 1), (1, 1), (1, 5), (1, 4), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2)]
How can I report an error if (1,1) in the above list or some other tuple occurs more than once 如果上面的列表中的(1,1)或其他元组多次出现,我该如何报告错误
Similarly for the list 同样的列表
lt22 = [['a', (1,1)], ['a', (1,2)], ['a', (1,2)], ['a', (1,3)], ['b', (2,1)], ['b', (2,2)], ['b', (2,2)]]
How to report an error if ['a', (1,2)] or any other element occurs more than once 如果['a',(1,2)]或任何其他元素出现多次,如何报告错误
Use a set and a loop; 使用set和loop; the set will let you know if you've seen an element before: 如果您之前看过一个元素,该集将告诉您:
seen = set()
for el in lt1:
if el in seen:
raise ValueError, 'More than one %r in your list' % (el,)
seen.add(el)
Note that for mutable elements such as found in your second list, you want to convert these to non-mutable variants such as tuples first: 请注意,对于可变元素(例如在第二个列表中找到的元素),您希望首先将这些元素转换为非可变变体,例如元组:
seen = set()
for el in lt22:
el = tuple(el)
if el in seen:
raise ValueError, 'More than one %r in your list' % (el,)
seen.add(el)
If you just want to detect it, not see exactly what element(s) occur more than once, you can just do: 如果您只是想检测它,而不是确切地看到哪些元素出现过多次,您可以这样做:
if len(lt1) != len(set(lt1)):
# Not all unique
In the second example you need to map the lists to tuples before converting to a set: 在第二个示例中,您需要在转换为集合之前将列表映射到元组:
if len(lt22) != len(set(map(tuple, lt22))):
# Not all unique
If you want to know how many times each item occurred, use collections.Counter
, which was introduced in python 2.7: 如果你想知道每个项目发生了多少次,请使用在python 2.7中引入的collections.Counter
:
>>> from collections import Counter
>>> {k: d for k, d in Counter(lt1).items() if d > 1}
{(1, 1): 2}
Again, you must map lt22
to tuple
before using it to have it work. 同样,在使用它之前,必须将lt22
映射到tuple
才能使其工作。
If you just need a list of which items occur more than once, Martijns solution is probably the most efficient at that particular task. 如果您只需要列出哪些项目不止一次,Martijns解决方案可能是该特定任务中最有效的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.