gpt4 book ai didi

python - 如何使用字典数组的条件从同一字典中的另一个数组中提取元素?

转载 作者:太空宇宙 更新时间:2023-11-04 07:04:59 24 4
gpt4 key购买 nike

我有一个数组字典。

mydict={'a':[45,65,78,32], 'b':['red','blue','green','yellow'], 'c':[3.4, 4.5, 6.5, 7.6]}

mydict['a'] 大于 35 时,我想提取 mydict['b'] 的元素。我要

myarr = ['red','blue','green']

我试过了-

myarr = [mydict['b'] for num in mydict['a'] num > 35]

我不想走枚举和保存索引以及使用索引的 C++/C 路线。听起来不像 Python。

我该怎么做?

最佳答案

如果 dict['a'] > 35 的值,则创建一个新的 list:

mydict = {'a':[45,65,78,32], 'b':['red','blue','green','yellow'], 'c':[3.4, 4.5, 6.5, 7.6]}

Python 3.x:

使用 itertools.zip_longest(*iterables, fillvalue=None) :

来自docs :

Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted

print([y for x,y in zip_longest(mydict['a'],mydict['b']) if x > 35])

Python 2.x:

使用 itertools.izip_longest(*iterables[, fillvalue])

print([y for x,y in izip_longest(mydict['a'],mydict['b']) if x > 35])

输出:

['red', 'blue', 'green']

编辑:

zip()zip_longest() 有什么区别?

考虑以下列表:

x = [1,2,3,4,5]    
y = ['a','b','c']

for a,b in zip(x,y):
print(a,b)

输出:

1 a
2 b
3 c

它显然跳过了 x 中的元素 4,5,因为它在 y 中找不到对应的元素。

使用 zip_longest():

x = [1,2,3,4,5]    
y = ['a','b','c']

for a,b in zip_longest(x,y):
print(a,b)

输出:

1 a
2 b
3 c
4 None
5 None

它没有跳过 x 中的元素,而是用 None 填充了 y 中缺失的元素。

关于python - 如何使用字典数组的条件从同一字典中的另一个数组中提取元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55729180/

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