繁体   English   中英

等同于“如果”的Python

[英]Python “and if” equivalent

假设“ mylist”可以包含值“ video”,“ audio”,“ visual”或全部三个。 如果希望在“ mylist”中找到一个字符串,我希望脚本将匹配的数据追加到“文件”列表中,如果“ mylist”中只有一个字符串,则可以工作,但是如果有多个字符串,则只有第一个字符串可以工作在“ mylist”中匹配。 有什么我可以代替“ 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()

只需使用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')

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

为什么不只是呢? 你想,如果它发生各种情况。 每个子句之间没有关系。 :)

暂无
暂无

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

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