我有以下代码:
quantity_of_units = int(funding_time_left.split[0])
unit_of_measurement = funding_time_left.split()[1]
now = datetime.datetime.now()
if unit_of_measurement == 'days':
end = (now + timedelta(days=quantity_of_units)).strftime('%Y-%m-%d')
elif unit_of_measurement == 'hours':
end = (now + timedelta(hours=quantity_of_units)).strftime('%Y-%m-%d')
else: # unit_of_measure == 'minutes'
end = (now + timedelta(minutes=quantity_of_units)).strftime('%Y-%m-%d')
funding.append([aeles.get_attribute('href'), end])
我想知道是否可以使用变量(unit_of_measurement
)作为关键字参数(days
,hours
,minutes
)?
如果确实有可能,我可以完全废弃if elif else
块并将其全部变成一行。下面是我希望做的。
quantity_of_units = int(funding_time_left.split[0])
unit_of_measurement = funding_time_left.split()[1]
now = datetime.datetime.now()
end = (now + timedelta(unit_of_measurement=quantity_of_units)).strftime('%Y-%m-%d')
funding.append([aeles.get_attribute('href'), end])
答案 0 :(得分:1)
您可以使用**
在参数中解包dict
,将其设置为关键字参数。
timedelta(**{unit_of_measurement: quantity_of_units})
之所以起作用,是因为它解压缩到:
timedelta(<unit_of_measurement>=quantity_of_units)
<unit_of_measurement>
是minutes
,seconds
,days
...
因此,您可以将if... elif... else...
语句替换为:
end = (now + timedelta(**{unit_of_measurement: quantity_of_units})).strftime('%Y-%m-%d')