简体   繁体   中英

Python “and if” equivalent

assume "mylist" can contain the values "video", "audio", "visual" or all three. I want my script to append the matching data to the list "files" if the string is found in"mylist" this works if there is only one string in "mylist", but if there is more than one string, only the first string in "mylist" gets matched. Is there something I could use instead of "elif" that is equivalent to "and if"?

 if request.method == 'POST':
    mylist = request.POST.getlist('list')
    files = []
    if 'video' in mylist:
      files.append('/home/dbs/public_html/download/codex/codex.html')
    elif 'audio' in mylist:
      files.append('/home/dbs/public_html/download/audio/audio_player.html')
    elif 'visual' in mylist:
      files.append('/home/dbs/public_html/download/visual/visual.html')
    return HttpResponse(files)
  else:
    return http.HttpResponseForbidden()

Simply use if instead of elif .

if 'video' in mylist:
    files.append('/home/dbs/public_html/download/codex/codex.html')
if 'audio' in mylist:
    files.append('/home/dbs/public_html/download/audio/audio_player.html')
if 'visual' in mylist:
    files.append('/home/dbs/public_html/download/visual/visual.html')

You could also use a mapping object and a loop which would be nicer in case there were more than a few items since you don't have to repeat the `... in mylist code:

paths = {
    'video': '/home/dbs/public_html/download/codex/codex.html',
    'audio': '/home/dbs/public_html/download/audio/audio_player.html',
    'visual': '/home/dbs/public_html/download/visual/visual.html'
}

files += [path for key, path in paths.iteritems() if key in mylist]

Why not just if? You want each case if it occurs. There is no relationship between each clause. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM