Python 条件如果多个列表是唯一的

Python 条件如果多个列表是唯一的,python,conditional-statements,Python,Conditional Statements,我试着寻找答案,但找不到正确的答案。 假设我有这个: list=['f','f','f','f','r','r','r','r','b','b','b','b','l','l','l','l','t','t','t','t', 'u','u','u','u'] c1=[list[0],list[13],list[18]] c2=[list[1],list[4],list[19]] c3=[list[5],list[8],list[17]] c4=[list[9],list[12],l

我试着寻找答案,但找不到正确的答案。 假设我有这个:

list=['f','f','f','f','r','r','r','r','b','b','b','b','l','l','l','l','t','t','t','t',
      'u','u','u','u']
c1=[list[0],list[13],list[18]]
c2=[list[1],list[4],list[19]]
c3=[list[5],list[8],list[17]]
c4=[list[9],list[12],list[16]]

#if c1,c2,c3,c4 are unique
#do something
我如何比较这4个列表是否唯一?

如果“唯一”是指每个位置不包含相同的值,那么类似的方法应该有效:

if len(set(map(tuple, [c1, c2, c3, c4]))) == 4:
  # All four lists are unique
if (tuple(c1) != tuple(c2) != tuple(c3) != tuple(c4)):
    print 'All are unique!'
else:
    raise 'Oh no, they are not all unique!'
请注意,在此场景中,
[1,2]
[2,1]
是不同的。如果出于您的目的,这些都是相同的,那么您希望这样:

if len(set(map(frozenset, [c1, c2, c3, c4]))) == 4:
  # All four lists are unique

如果您需要对“唯一”的其他定义,那么您需要更清楚地说明您的问题。

由于顺序不重要,您可能需要对子列表进行排序,然后检查这些子列表的集合是否与原始排序列表的长度相同:

if max(len(c1), len(c2)) != len(set(c1) & set(c2))\
        and max(len(c1), len(c3)) != len(set(c1) & set(c3))\
        and max(len(c1), len(c4)) != len(set(c1) & set(c4))\
        and max(len(c2), len(c3)) != len(set(c2) & set(c3))\
        and max(len(c3), len(c4)) != len(set(c3) & set(c4)):
    print("Do something.")
else:
    print("Do something else.")
ordered = [tuple(sorted(l)) for l in [c1, c2, c3, c4]]
# [('f', 'l', 't'), ('f', 'r', 't'), ('b', 'r', 't'), ('b', 'l', 't')]

unique = len(set(ordered)) == len(ordered)
# True 

我通常不喜欢一句话,但我相信这应该是可行的:

if len(set(map(tuple, [c1, c2, c3, c4]))) == 4:
  # All four lists are unique
if (tuple(c1) != tuple(c2) != tuple(c3) != tuple(c4)):
    print 'All are unique!'
else:
    raise 'Oh no, they are not all unique!'

不要隐藏内置组件。使用合理的变量名,如
lst
L
,而不是
list
。此外,还要精确定义唯一性。秩序重要吗?或者
['r','b','r']
等同于
['b','r','r']
?那么期望的输出是什么?@jpp是的,但我使用了'list'作为示例。不,秩序不存在matter@U9-转发返回一条错误消息,如果至少有两个列表相似(无论顺序如何,元素都相同)@Plagga好的,那么顺序不重要,我应该更精确。使用frozenset很有效。感谢失败在
c1=['a','b','b'];c2=['a','b','b']
c1=列表('aab')上失败;c2=list('abb')
您不能像以前那样调用字符串上的list对象,而且如果您像我一样使用set,我的代码应该适用于这些情况。是的,我忘了OP一直在隐藏内置项。然而,您的代码在我演示的用例中失败了,这并不完全是一个模糊的边缘用例。
set(['a','a','b'])!=集合(['a','b','b'])
的计算结果为
False
,即使这两个集合彼此是唯一的。啊,太棒了!对不起,我一开始误解了你的意思。