如何保持具有唯一ID的嵌套列表?

2024-04-25 08:13:11 发布

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

nested_list = [['123','hello','true'],['234','excuse','true'],['123,''hello','true'],['254','hello','false']]

我有一张名单。每个嵌套列表有三个值、一个ID和两个文本字符串

我只想保留那些具有唯一ID的嵌套列表

我尝试将其设置为一个集合,但是,如果将其设置为一个集合,则会丢失输出中所需的第四个嵌套列表,因为它的ID是唯一的

output = [['123','hello','true'],['234','excuse','true'],['254','hello','false']]

我怎样才能做到这一点


Tags: 字符串文本idfalsetruehello列表output
3条回答

最快的方法是使用numpy.unique()函数。它允许您标识唯一元素的索引。不需要循环

nested_list = [['123','hello','true'],['234','excuse','true'], 
   ['123','hello','true'],['254','hello','false']]

import numpy as np
arr = np.array(nested_list)
_ , idx = np.unique(arr[:,0],return_index = True)

print(arr[idx])

输出:

[['123' 'hello' 'true']
 ['234' 'excuse' 'true']
 ['254' 'hello' 'false']]

您需要将内部列表转换为元组:

nested_list = [['123','hello','true'],['234','excuse','true'],['123','hello','true'],['254','hello','false']]


def f7(seq):
    seen = set()
    seen_add = seen.add
    return [x for x in seq if not (tuple(x) in seen or seen_add(tuple(x)))]


print(f7(nested_list))

输出:

[['123', 'hello', 'true'], ['234', 'excuse', 'true'], ['254', 'hello', 'false']]

我的意思是,最简单的方法就是遍历它们并创建一个新列表:

nested_list = [['123','hello','true'],
               ['234','excuse','true'],
               ['123','hello','true'],
               ['254','hello','false']]
visited_ids = set()
unique_nested_list = []
for thing in nested_list: 
  if thing[0] not in visited_ids:
    visited_ids.add(thing[0])
    unique_nested_list.append(thing)
print(unique_nested_list)

相关问题 更多 >