gpt4 book ai didi

python - 在 python 中的两个列表列表之间查找公共(public)元素的最快方法

转载 作者:太空狗 更新时间:2023-10-30 02:53:43 24 4
gpt4 key购买 nike

我有一个列表如下。

mylist = 
[
[
[
"chocolate_pudding",
920.8000000000001
],
[
"caramel_pudding",
345.59999999999997
],
[
"pudding",
248.0
],
[
"banana_pudding",
27.599999999999998
]
],
[
[
"biscuits",
190.8
],
[
"chocolates",
33.599999999999994
],
[
"chocolate_pudding",
920.8000000000001
]
],
[
[
"tiramusu",
145.8
]
],
[
[
"cakes",
139.29999999999998
]
],
[
[
"butter_cakes",
133.0
]
],
[
[
"chocolate_pudding",
920.8000000000001
]
]
]

我想找到在列表中出现多次的元素(例如,["chocolate_pudding", 920.8000000000001])并想删除重复的元素,同时保留第一个条目。

所以,我的输出应该如下所示。

mylist = 
[
[
[
"chocolate_pudding",
920.8000000000001
],
[
"caramel_pudding",
345.59999999999997
],
[
"pudding",
248.0
],
[
"banana_pudding",
27.599999999999998
]
],
[
[
"biscuits",
190.8
],
[
"chocolates",
33.599999999999994
]
],
[
[
"tiramusu",
145.8
]
],
[
[
"cakes",
139.29999999999998
]
],
[
[
"butter_cakes",
133.0
]
]
]

我一直在尝试的代码如下。

mylist_copy = mylist

for item in mylist:
myindex = mylist.index(item)
#print(item)

for single_item in item:
#print(single_item)
for item_copy in mylist_copy:
if mylist_copy.index(item_copy) != myindex:
if single_item in item_copy:
print(single_item)

因为它有很多 for 循环,所以我想要一种有效的方法来完成它。注:我也试过了;

mylist_copy = mylist

for item in mylist:
myindex = mylist.index(item)
for item_copy in mylist_copy:
if mylist_copy.index(item_copy) != myindex:
print(set(item).intersection(item_copy))

但是,交集不支持列表。

在 python 中有没有简单快捷的方法?

最佳答案

使用 set() 对象并保留子列表的顺序:

mylist = [[["chocolate_pudding", 920.8000000000001], ["caramel_pudding", 345.59999999999997], 
["pudding", 248.0], ["banana_pudding", 27.599999999999998]], [["biscuits", 190.8],
["chocolates", 33.599999999999994], ["chocolate_pudding", 920.8000000000001]],
[["tiramusu", 145.8]], [["cakes", 139.29999999999998]], [["butter_cakes", 133.0]],
[["chocolate_pudding", 920.8000000000001]]]

result, foods = [], set()
for sub_l in mylist:
new_sublist = []
for i in sub_l:
if i[0] not in foods: # on the 1st occurrence of `foodstuff` name
new_sublist.append(i)
foods.add(i[0]) # add `foodstuff` into set of unique foods
if new_sublist: result.append(new_sublist)

print(result)

输出:

[[['chocolate_pudding', 920.8000000000001], ['caramel_pudding', 345.59999999999997], ['pudding', 248.0], ['banana_pudding', 27.599999999999998]], [['biscuits', 190.8], ['chocolates', 33.599999999999994]], [['tiramusu', 145.8]], [['cakes', 139.29999999999998]], [['butter_cakes', 133.0]]]

关于python - 在 python 中的两个列表列表之间查找公共(public)元素的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48536762/

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