[英]getting max sublist based on value from other list in python
want to get sublist which has max value on specified index based on condition. 想要根据条件得到在指定索引上具有最大值的子列表。
mainlist=[[['RD-2', 'a', 120], ['RD-2', 'b', 125], ['RD-2', 'c', 127]], [['RD-3', 'a', 120], ['RD-3', 'b', 140]], [['RD-5', 'a', 120]],[['RD-7', 'a', 122]]]
and another list 和另一个清单
baselist=[['RD-2', 100],['RD-3', 200],['RD-5', 240]]
for every first sub-element in baselist, i need the 1 complete sublist from mainlist which has max value in 2nd index position. 对于baselist中的每个第一个子元素,我需要来自mainlist的1个完整子列表,其在第二个索引位置具有最大值。 the output should be 输出应该是
flist=[['RD-2', 'c', 127],['RD-3', 'b', 140],['RD-5', 'a', 120]]
help me. 帮我。
Try this: 尝试这个:
flist = []
for item in baselist:
for i in mainlist:
if i[0][0] ==item[0]:
flist.append(max(i, key=lambda x:x[2]))
the flist
will be: flist
将是:
[['RD-2', 'c', 127], ['RD-3', 'b', 140], ['RD-5', 'a', 120]]
you can also use itertools.product
to simplyfy for
loops a little: 你也可以使用itertools.product
简单地for
循环做一点:
from itertools import product
flist = []
for i, item in product(mainlist,baselist):
if i[0][0] ==item[0]:
flist.append(max(i, key=lambda x:x[2]))
or also in just one line: 或者也只是一行:
flist = [max(i, key=lambda x:x[2]) for i, item in product(mainlist,baselist) if i[0][0] == item[0]]
A bit more compact but with the same outcome using list comprehension: 更紧凑,但使用列表理解具有相同的结果:
max_entries = [max(x, key=lambda x:x[2]) for x in mainlist]
flist = [max_entry for max_entry in max_entries for base_entry in baselist if max_entry[0]==base_entry[0]]
Here's a way using a list comprehension: 这是使用列表理解的一种方式:
base = list(zip(*baselist))[0]
[max(i, key=lambda x:x[2]) for i in mainlist if i[0][0] in base]
[['RD-2', 'c', 127], ['RD-3', 'b', 140], ['RD-5', 'a', 120]]
I would first store you max lists in a dictionary, then just reference that dictionary later to build the new list: 我会先在字典中存储最大列表,然后稍后再引用该字典来构建新列表:
from operator import itemgetter
mainlist = [
[["RD-2", "a", 120], ["RD-2", "b", 125], ["RD-2", "c", 127]],
[["RD-3", "a", 120], ["RD-3", "b", 140]],
[["RD-5", "a", 120]],
[["RD-7", "a", 122]],
]
baselist = [["RD-2", 100], ["RD-3", 200], ["RD-5", 240]]
d = {}
for sublist in mainlist:
k = sublist[0][0]
d[k] = max(sublist, key=itemgetter(2))
flist = [d.get(k) for k, _ in baselist]
print(flist)
# [['RD-2', 'c', 127], ['RD-3', 'b', 140], ['RD-5', 'a', 120]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.