gpt4 book ai didi

python - 两个列表之间的最大值及其索引

转载 作者:行者123 更新时间:2023-12-01 00:46:58 25 4
gpt4 key购买 nike

我有一个包含值列表的嵌套字典,我想要- 两个列表之间的最大索引值- 每个最大值的“id”(通过 id 我的意思是来自哪个列表的值以及它的索引)。

我已经有了两个列表之间的索引最大值,我需要的是“id”。

#create dictionary:

test = {}
test['A'] = {}
test['A']['number'] = [2,2,3]
test['A']['id'] = ['x','y','z']
test['B'] = {}
test['B']['number'] = [1,3,2]
test['B']['id'] = ['a','b','c']

#this the maximum index-wise value between the two lists
max_list = [max(*l) for l in zip(test['A']['number'], test['B']['number'])]

print(max_list)

我想要的是另一个包含以下内容的列表:['x','b','z']

最佳答案

制作 idnumber 的内部 zip,以便我们知道哪个 id 属于哪个号码,

然后将 max 与自定义键函数(按数字)一起使用,然后拆分它们:

test = {}
test['A'] = {}
test['A']['number'] = [2,2,3]
test['A']['id'] = ['x','y','z']
test['B'] = {}
test['B']['number'] = [1,3,2]
test['B']['id'] = ['a','b','c']

tuple_list = [max(*l, key=lambda t: t[1]) for l in zip(zip(test['A']['id'],test['A']['number']), zip(test['B']['id'],test['B']['number']))]
max_num_list = [t[1] for t in tuple_list]
max_id_list = [t[0] for t in tuple_list]

print(max_num_list)
print(max_id_list)

输出:

[2, 3, 3]
['x', 'b', 'z']

关于python - 两个列表之间的最大值及其索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56899084/

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