查找元素值是唯一的,列表中的所有元素都相同

时间:2018-05-21 04:58:11

标签: python python-2.7

查找元素值是唯一的,列表中的所有元素都相同。

  >>> a = ['1','1']
  >>> all(x == a[0] for x in a)
  True
  >>> a = ['1','2']
  >>> all(x == a[0] for x in a)
  False
  >>> a = ['1-2-3','1-2-3']
  >>> all(x == a[0] for x in a)
  True

  #### Diffent Example #####################
  >>> a = ['1-2-2','1-2-2']
  >>> all(x == a[0] for x in a)
  True
  Expected Output False.

  any elements must contain unique values, but here it is repeated that is 2-2.

列表格式始终:

   a = ["1", "2", "3","4"]
   b = ["1-2-3", "1-2-2"] # That is dash separated 

1 个答案:

答案 0 :(得分:2)

您可以尝试使用其他条件在-上进行拆分,并检查长度是否与set相匹配,与list相比,即添加(len(x.split('-')) == len(set(x.split('-')))

>>> a = ['1-2-2','1-2-2']
>>> all((x == a[0]) and (len(x.split('-')) == len(set(x.split('-')))) for x in a)

结果:

False

其他例子:

>>> a = ['1-2-3','1-2-3']
>>> all((x == a[0]) and (len(x.split('-')) == len(set(x.split('-')))) for x in a)

结果:

True