首页 > 解决方案 > 如何在一行python3中组合多个if语句

问题描述

嗨,我是 python 和编程的新手,我将如何结合这些:

if "Web" in source:
    source = "WEB"
if ((source == "Blu-ray") and (other == "Remux") and (reso == "1080p")):
    reso = "BD Remux"
if "DVD" in name:
    reso = "DVD Remux"
if ((source == "Ultra HD Blu-ray") and (other == "Remux") and (reso == "2160p")):
    reso = "UHD Remux"
if source == "Ultra HD Blu-ray":
    source = "Blu-ray"

标签: python-3.xif-statement

解决方案


您可以使用该elif子句if通过额外条件扩展您的语句:

mystring='what will it print?' 

if   mystring == 'hello':
     print('world!')
elif mystring == 'good':
     print('bye!')
elif mystring == 'how':
     print('are you?')
else:
     print('I ran out of ideas!')
 [out]: I ran out of ideas!

稍微重写您的示例可能如下所示:

source='Ultra HD Blu-ray'
name='DVD'
reso='2160p'
other='Remux'

resos={'1080p':'BD Remux','2160p':'UHD Remux'}

if "Web" in source:
    source = "WEB"
elif "Blu-ray" in source and other == "Remux":
    source = "Blu-ray"
    reso   = resos.get(reso,'UNDEFINED')
elif "DVD" in name:
    reso = "DVD Remux"

print(source, name, reso)
[out]: Blu-ray DVD UHD Remux

请注意,我已将resos字典用作两个if语句的替代品,有关此内容的更多详细信息请参见此处


推荐阅读