具有一组集合,如下所示:
expiry = [{'20180830', '20180928', '20181025'},
{'20180830', '20180927', '20181026'},
{'20180830', '20180927', '20181025'}]
和一个功能
def get_dte(Expiry):
exp_date = datetime.strptime(Expiry, '%Y%m%d')
dte = (exp_date- datetime.now()).days
return dte
如何以相同形式的输入(集合列表)获取函数的输出?
[get_dte(i) for elem in expiry for i in elem]
产生:
[61, 90, 33, 61, 89, 34, 61, 89, 33]
...并且需要用于:
[{61, 90, 33}, {61, 89, 34}, {61, 89, 33}]
答案 0 :(得分:2)
您需要分别迭代到期的每个元素:
>>> [{get_dte(j) for j in i} for i in expiry]
[{33, 62, 89}, {33, 61, 90}, {33, 61, 89}]
答案 1 :(得分:0)
您只需要对列表理解进行一些修改。
尝试:
from datetime import datetime
expiry = [{'20180830', '20180928', '20181025'},
{'20180830', '20180927', '20181026'},
{'20180830', '20180927', '20181025'}]
def get_dte(Expiry):
exp_date = datetime.strptime(Expiry, '%Y%m%d')
dte = (exp_date- datetime.now()).days
return dte
print( [{get_dte(i) for i in elem } for elem in expiry] )
输出:
[{89, 33, 62}, {33, 90, 61}, {89, 33, 61}]