从python lis中查找唯一值

2024-03-29 09:47:27 发布

您现在位置:Python中文网/ 问答频道 /正文

如何为列表列表查找唯一项?你知道吗

在下面的例子中,我只需要两个项目。你知道吗

mylist=[[' Dish Towel .\n', '1.000', '149.000'],
 [' Dish Towel .\n', '1.000', '149.000'],
 [' Kitchentowel(mix designs) .\n', '1.000', '99.000'],
 [' Kitchentowel(mix designs) .\n', '1.000', '99.000']]

预期结果:

newlist=[[' Dish Towel .\n', '1.000', '149.000'],
 [' Kitchentowel(mix designs) .\n', '1.000', '99.000']]

我试过了,但我打错了。你知道吗

  output = set()
  for x in mylist:
       output.add(x)
  print output

Tags: 项目inadd列表foroutputtowel例子
2条回答

您可以使用set保留唯一项:

>>> set(map(tuple,mylist))
set([(' Kitchentowel(mix designs) .\n', '1.000', '99.000'), (' Dish Towel .\n', '1.000', '149.000')]) 

请注意,由于set只接受可哈希对象,因此需要将列表转换为元组,然后使用set

你可以尝试以下方法:

output = []
for x in mylist:
    if x not in output:
        output.append(x)
print output

相关问题 更多 >