我有一个带有4个参数的函数:
def uploadDatabase(user,filter1,filter2, name):
"""uploads playlists to database
if a playlist satisfying both filters is not long enough,
we pick a playlist based on one single filter"""
playlist_filter1 = [x['track'] for x in filter1]
playlist_filter2 = [x['track'] for x in filter2]
playlist_both_filters = [x['track'] for x in filter2 if x['track'] in [y['track'] for y in filter1]]
#create an empty dict for user as key
double_filter = {str(user):{}}
single_filter1 = {str(user):{}}
single_filter2 = {str(user):{}}
#set initial playback number for each track
count = 1
#set counts to tracks
double_filter[str(user)] = dict(zip(playlist_both_filters, [count for i in playlist_both_filters]))
db_double = double_filter
#set counts to tracks
single_filter1[str(user)] = dict(zip(playlist_filter1, [count for i in playlist_filter1]))
db_single1 = single_filter1
(...)
但是,有时候filter2
将不会传递:
uploadDatabase(user,energy_playlist, None, 'my playlist')
我如何修复uploadDatabase()
并告诉它忽略None Type
被分配给变量playlist_filter2
和double_filter
,因为两者都需要有效lists
?
答案 0 :(得分:0)
您可以通过执行以下操作将None
类型转换为两个过滤器的有效空列表:
playlist_filter1 = [x['track'] for x in filter1] if filter1 is not None else []
playlist_filter2 = [x['track'] for x in filter2] if filter2 is not None else []
而不是:
playlist_filter1 = [x['track'] for x in filter1]
playlist_filter2 = [x['track'] for x in filter2]
答案 1 :(得分:0)
如果我理解正确,你想检查是否传递参数 filter2 。
这样做很简单,你实际上给它runserver
的默认值,然后在代码中检查参数是否为None
。
None
当你使用这个函数时,你可以传递filter2,它会覆盖默认的def uploadDatabase(user,filter1,filter2=None, name):
if not filter2:
# filter2 argument in not passed
else:
# filter2 argument is there.
值,或者只是不传递它,它将是None