我有两个相同代码的版本,一个短版本和一个长版本。我真的想使用短文,因为我不知道用户输入字典的值是多少。
所以长版本是:
angles_1= {'angle_1': 'abc', 'angle_2': 'acb', 'angle_3': 'cab'}
shared_vertex = 'c'
print(angles_1['angle_1'][1])
print(angles_1['angle_2'][1])
print(angles_1['angle_3'][1])
if shared_vertex == (angles_1['angle_1'][1]):
print("{}".format(angles_1['angle_1']), 'is a vertically opposite angle')
elif shared_vertex == (angles_1['angle_2'][1]):
print("{}".format(angles_1['angle_2']), 'is a vertically opposite angle')
elif shared_vertex == (angles_1['angle_3'][1]):
print("{}".format(angles_1['angle_3']), 'is a vertically opposite angle')
else:
print('There are no vertically opposite angles')
简短版本是:
loop = 3
for n in range(loop):
def to_ordinal(n:int) -> str:
endings = {1: "", 2: "", 3: ""}
if shared_vertex == (angles_1['angle_{}'.format(to_ordinal(n))[1]]):
print("{}".format(angles_1['angle_{}'.format(to_ordinal(n))]), 'is a vertically opposite angle')
else:
print("{}".format(angles_1['angle_{}'.format(to_ordinal(n))]), 'is not a vertically opposite angle')
现在短版本支持KeyError的错误。
我能帮忙吗?
答案 0 :(得分:1)
你可以在相反的角度迭代角度和break
:
angles_1= {'angle_1': 'abc', 'angle_2': 'acb', 'angle_3': 'cab'}
shared_vertex = 'c'
for vertices in angles_1.values():
if vertices[1] == shared_vertex:
print(vertices, 'is a vertically opposite angle')
break
else:
print('There are no vertically opposite angles')
我在循环上使用else
子句,你可以阅读它here。
另一种方法是制作一个临时字典并.get
一个角度:
angle = {a[1]: a for a in angles_1.values()}.get(shared_vertex)
if angle:
print(angle, 'is a vertically opposite angle')
else:
print('There are no vertically opposite angles')
答案 1 :(得分:0)
我猜你几乎没有为你的词典和打印功能关闭括号。
更新的代码:
loop = 3
for n in range(loop):
def to_ordinal(n:int) -> str:
endings = {1: "", 2: "", 3: ""}
if shared_vertex == (angles_1['angle_{}'.format(to_ordinal(n))][1]):
print("{}".format(angles_1['angle_{}'.format(to_ordinal(n))]), 'is a vertically opposite angle')
else:
print("{}".format(angles_1['angle_{}'.format(to_ordinal(n))]), 'is not a vertically opposite angle')