简体   繁体   English

等同于“如果”的Python

[英]Python “and if” equivalent

assume "mylist" can contain the values "video", "audio", "visual" or all three. 假设“ mylist”可以包含值“ video”,“ audio”,“ visual”或全部三个。 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. 如果希望在“ mylist”中找到一个字符串,我希望脚本将匹配的数据追加到“文件”列表中,如果“ mylist”中只有一个字符串,则可以工作,但是如果有多个字符串,则只有第一个字符串可以工作在“ mylist”中匹配。 Is there something I could use instead of "elif" that is equivalent to "and if"? 有什么我可以代替“ ifif”的“ elif”使用的吗?

 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代替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: 您还可以使用一个映射对象和一个循环,如果存在多个项目,则更好,因为您不必`... in mylist代码中重复`... in mylist

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. 每个子句之间没有关系。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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