这是我的一个个人项目,现在我的程序是一吨如果语句的基础上,我做了每一季的集编号(不同的季节有不同的集数)和标题字典。我得到了想要的结果,但是我一直在努力寻找一种更高级的方法,比如使用函数、列表或对象来更优雅地显示它,并且代码行更少。你知道吗
我一直试图通过google和教程找出如何使用其他方法之一,但我不知道如何将其应用到我的特定程序中,在没有所有这些单独if语句的情况下获得结果。你知道吗
epTitles1 = {"1" : "The Gang Gets Racist",
"2" : "Charlie Wants an Abortion",
"3" : "Underage Drinking: A National Concern",
"4" : "Charlie Has Cancer",
"5" : "Gun Fever",
"6" : "The Gang Finds a Dead Guy",
"7" : "Charlie Got Molested"}
epTitles2 = {"1" : "Charlie Gets Crippled",
"2" : "The Gang Goes Jihad",
"3" : "Dennis and Dee Go on Welfare",
"4" : "Mac Bangs Dennis' Mom" ,
"5" : "Hundred Dollar Baby" ,
"6" : "The Gang Gives Back",
"7" : "The Gang Exploits a Miracle",
"8" : "The Gang Runs for Office",
"9" : "Charlie Goes America All Over Everybody's Ass",
"10" : "Dennis and Dee Get a New Dad"}
x = int(input("Enter a season between 1 and 13 or 0 for random season: "))
print("You selected season:", x)
if x == 0:
randomSeason = random.randint(1,13)
print("Random season:", randomSeason)
if randomSeason == 1:
episode = random.randint(1,7)
print("Episode:", episode)
if episode == 1:
print(epTitles1["1"])
elif episode == 2:
print(epTitles1["2"])
elif episode == 3:
print(epTitles1["3"])
elif episode == 4:
print(epTitles1["4"])
elif episode == 5:
print(epTitles1["5"])
elif episode == 6:
print(epTitles1["6"])
elif episode == 7:
print(epTitles1["7"])
if randomSeason == 2:
episode = random.randint(1,10)
print("Episode:", episode)
if episode == 1:
print(epTitles2["1"])
elif episode == 2:
print(epTitles2["2"])
elif episode == 3:
print(epTitles2["3"])
elif episode == 4:
print(epTitles2["4"])
# same pattern continues for each season (13 seasons)
我只想学习和理解什么样的方法/方法可以帮助我以更实际的方式压缩代码,以及如何做到这一点。你知道吗
将数据存储在一个dict的dict中。外文记载了季节,内文记载了本部分的零件号和名称:
以下是扩展dict理解后的数据:
多输出:
如果你不喜欢“裸体”字典,你也可以考虑使用named tuples。你知道吗
为了让它成为用户输入的证明,而不是使用dict中的随机数:
将为任何不合适的键打印
"Does not exist"
你可以这样做你的字典
或者你甚至可以有一个列表字典(或列表列表)为所有的季节
然后你可以通过这种方式访问它们
您还可以将随机选择的事件范围保存在一个元组的dict中,以进一步最小化代码,因此最终代码将如下所示
谢谢你的建议!我把所有的片段放在一本字典里,用元组作为键,就可以大大缩短它。然后我就可以根据用户的输入过滤出按键,打印出这一季和这一集的标题
相关问题 更多 >
编程相关推荐