我想基于类似的条件,通过不同数量的类似参数在查询上调用group_by函数:
if hour:
q = q.group_by(extract('year', Action.action_date_time),
extract('month', Action.action_date_time),
extract('day', Action.action_date_time),
extract('hour', Action.action_date_time))
elif day:
q = q.group_by(extract('year', Action.action_date_time),
extract('month', Action.action_date_time),
extract('day', Action.action_date_time))
等等。
如何让这段代码变得更加pythonic?
答案 0 :(得分:2)
您可以使用列表理解:
by_hour = ['year', 'month', 'day', 'hour']
by_day = ['year', 'month', 'day']
if hour:
q = q.group_by(*[extract(x, Actin.action_date_time) for x in by_hour])
elif day:
q = q.group_by(*[extract(x, Actin.action_date_time) for x in by_day])
您还可以使用字典来存储不同的可能性:
by_ = {
'hour': ['year', 'month', ...],
'day': ['year', ...],
}
使用这个特定的有序数据,您还可以使用一个列表并对其进行切片:
time = ['year', 'month', 'day', 'hour']
if hour:
q = q.group_by(*[extract(x, Action.action_date_time) for x in time])
elif day:
q = q.group_by(*[extract(x, Action.action_date_time) for x in time[:2]])
elif month:
q = q.group_by(*[extract(x, Action.action_date_time) for x in time[:1]])
答案 1 :(得分:1)
let button = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.add, target: self, action: #selector(buttonTapped(button:)))
self.navigationItem.rightBarButtonItem = button
func buttonTapped(button: UIBarButtonItem) {
print("bar button taped")
}
答案 2 :(得分:1)
基于@grepe的答案和你的评论,如果你想摆脱重复,我想你可以尝试这样的事情:
grouping = [extract('year', Action.action_date_time),
extract('month', Action.action_date_time),
extract('day', Action.action_date_time)]
if hour:
grouping.append(extract('hour', Action.action_date_time))
q = q.group_by( *grouping )