我是初学者程序员。我正在上课。我在课程的框架内解决了这个问题,但我想让我的解决方案更加美观和优化。如何改进和简化我的代码?
一个任务:
输入是数字 n 然后 n 行,格式如下: 'Zenith;3;Spartak;1' 你需要编写一个程序来计算所有匹配的结果,并以下列格式显示结果:
球队:Total_games 胜 平 负 Total_points
我的决定:
n = int(input())
x = [input().split(';') for i in range(n)]
res = {}
g = 1
wp = 3
for i in x:
if int(i[1]) > int(i[3]):
if i[0] in res:
z = res.get(i[0])
z[0] += g
z[1] += g
z[4] += wp
else:
res[i[0]] = [1, 1, 0, 0, 3]
if i[2] in res:
z = res.get(i[2])
z[0] += g
z[3] += g
else:
res[i[2]] = [1, 0, 0, 1, 0]
if int(i[1]) < int(i[3]):
if i[2] in res:
z = res.get(i[2])
z[0] += g
z[1] += g
z[4] += wp
else:
res[i[2]] = [1, 1, 0, 0, 3]
if i[0] in res:
z = res.get(i[0])
z[0] += g
z[3] += g
else:
res[i[0]] = [1, 0, 0, 1, 0]
if int(i[1]) == int(i[3]):
if i[0] in res:
z = res.get(i[0])
z[0] += g
z[2] += g
z[4] += g
else:
res[i[0]] = [1, 0, 1, 0, 1]
if i[2] in res:
z = res.get(i[2])
z[0] += g
z[2] += g
z[4] += g
else:
res[i[2]] = [1, 0, 1, 0, 1]
for i in res:
print(i, ' '.join(map(str, res.get(i))), sep=':')
感谢您的关注!
引入函数和数据结构是合理的。看看这个选项。
删除
if i[0] in res: else:使用defaultdict您可以从输出中删除 get 和 map。
if < , if >, if == 可以改成 if, elif, else
基于@becouse 的想法。希望以更惯用的风格。需要 python 3.7