gpt4 book ai didi

python - 字典列表中的唯一元素有效

转载 作者:太空宇宙 更新时间:2023-11-04 02:03:43 27 4
gpt4 key购买 nike

我想根据字段的值从字典列表中获取唯一元素并保留其他字段。

后面是我的数据格式。

[ {id:"1000", text: "abc", time_stamp: "10:30"},
{id:"1001", text: "abc", time_stamp: "10:31"},
{id:"1002", text: "bcd", time_stamp: "10:32"} ]

我想要如下输出:(基于文本是唯一的,但保留其他字段)

[ {id:"1000", text: "abc", time_stamp: "10:30"}, # earlier time stamp
{id:"1002", text: "bcd", time_stamp: "10:32"} ]

这里请注意,唯一性是基于文本的,我想保留 id 和 time_stamp 值。这个问题不同于Python - List of unique dictionaries之前问过的问题。

我试过:

方法一:仅从字典中收集文本值,将其转换为列表,将其传递给集合,并获得唯一的文本值,但我丢失了id和time_stamp。

方法2:我也提前试过了,我遍历了字典的列表,检查文本值是否存在于unique_list_of_text中,如果没有附加到list_of_unique_dictionary。但是这段代码花费了很多时间,因为我正在处理一个包含 350,000 条记录的数据集。有更好的方法吗?方法二的代码:

def find_unique_elements(list_of_elements):
no_of_elements = len(list_of_elements)
unique_list_of_text = []
unique_list_of_elements = []
for iterator in range(0, no_of_elements):
if not list_of_elements[iterator]['text'] in unique_list_of_text:
unique_list_of_full_text.append(list_of_elements[iterator]['text'])
unique_list_of_elements.append(list_of_elements[iterator])
return unique_list_of_elements

最佳答案

您可以从反向列表创建字典并从该字典中获取值:

id, text, time_stamp = 'id', 'text', 'timestamp'

l = [ {id:"1000", text: "abc", time_stamp: "10:30"},
{id:"1001", text: "abc", time_stamp: "10:31"},
{id:"1002", text: "bcd", time_stamp: "10:32"} ]

d = {i[text]: i for i in reversed(l)}
new_l = list(d.values())
print(new_l)
# [{'id': '1002', 'text': 'bcd', 'timestamp': '10:32'}, {'id': '1000', 'text': 'abc', 'timestamp': '10:30'}]

# if the order should be preserved
new_l.reverse()
print(new_l)
# [{'id': '1000', 'text': 'abc', 'timestamp': '10:30'}, {'id': '1002', 'text': 'bcd', 'timestamp': '10:32'}]

如果最终列表中的顺序很重要,请在 Python 3.6 及以下版本中使用 OrderedDict 而不是 dict

关于python - 字典列表中的唯一元素有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55187664/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com