我有一个数组字典。
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 中缺失的元素。
