感谢所有帮助
答案 0 :(得分:0)
我会试着给你一个不同的方法,看看这对你有帮助。
def main():
events = []
houses = []
scores = {} # key = House name, value = scores
print "Welcome!\n"
# create the houses
print "Please enter how many houses there is:"
n_houses = int(raw_input(">>"))
print "Please enter houses names:"
for n in range(n_houses):
print "House", n+1
house_name = raw_input(">>")
houses.append(house_name)
# create the events
print "Please enter the number of events there is"
n_events = int(raw_input(">>"))
print "Please enter the event names"
for n in range(n_events):
print "Event", n+1
event_name = raw_input(">>")
events.append(event_name)
# get the scores for each house for each event
for event in events:
for house in houses:
print "Please enter the score for House %s in the event %s"%(house, event)
score = int(raw_input(">>"))
# initialize the score with a empty list
if house not in scores:
scores[house] = []
# add the score list
scores[house].append(score)
print "\nThe result is:"
# process the result
for house, score in sorted(scores.items(),
key=lambda x: sum(x[1]),
reverse=True):
print "House %s. Total Score: %i"%(house, sum(score))
if __name__ == "__main__":
main()
你应该注意的第一件事是我没有使用全局,使用全局通常不赞成,它可能会导致不希望的数据交互。
此外,不要求像" XXX"为了打破循环,我向用户询问他之前要处理的输入数量,因此我可以循环显示这个数字并分别处理每个数据。
我对房子做同样的事情,我问那里有多少房子,然后是他们的名字。
接下来,我使用事件名称和房屋名称执行嵌套for循环。订单很重要,我们先处理每个事件。你可以先改变它来处理每个房子。
最后我处理得分。行for house, score in sorted(scores.items(), key=lambda x: sum(x[1]), reverse=True):
有点堵塞和高级,但它意味着:我想循环一个排序的项目列表,一次给我两个项目,项目名为house
和score
,它们将按函数sum(x[1])
排序,我希望以相反的顺序排序(或者最后一个显示在第一个中)。
key=lambda x: sum(x[1])
有点黑客,可以做得更好。 lambda 表示一个函数,它需要x
作为输入,x
在这种情况下是house, score
的元组,所以我想得分,所以我访问它使用x [1],因为我想要总和,我使用sum(x [1])。
用法:
Welcome!
Please enter how many houses there is:
>>2
Please enter houses names:
House 1
>>Gryffindor
House 2
>>Slytherin
Please enter the number of events there is
>>2
Please enter the event names
Event 1
>>Quidditch Match
Event 2
>>Duels
Please enter the score for House Gryffindor in the event Quidditch Match
>>100
Please enter the score for House Slytherin in the event Quidditch Match
>>90
Please enter the score for House Gryffindor in the event Duels
>>250
Please enter the score for House Slytherin in the event Duels
>>240
The result is:
House Gryffindor. Total Score: 350
House Slytherin. Total Score: 330
请注意,这是在Python 2.7上进行的,只需将raw_input
更改为input
,将print
更改为print()
< / p>
答案 1 :(得分:0)
LOWER_BOUND = 0
UPPER_BOUND = 100 # both in caps because this is a constant
def get_score(house_name, event_name):
# an extra argument so you can tell which event is being scored.
# removed the min, max cause we are using the constants!
score = -1
while score < LOWER_BOUND or score > UPPER_BOUND:
try:
score = int(input("Please enter score for %s in the event %s:" % (house_name, event_name)))
if score < LOWER_BOUND :
print ("Score is too low, minimum score is %i.\nPlease try again." % min_score)
if score > UPPER_BOUND:
print ("Score is too high, maximum score is %i\nPlease try again." % max_score)
except ValueError:
print("Invalid Input please enter an integer. Thanks")
return score # note the use of return to avoid using global
def get_number_of_events():
print("Please enter the number of events there is.")
while True:
try:
n_events = int(input(">>"))
except ValueError:
print("Enter only a number, Thanks.")
if n_events > 100:
print("WOW, that's a lot of events, please be reasonable. Thanks.")
elif n_events < 1:
# this is a different condition that would get a wrong error in your program,
# note the use of 'elif', in Python this an 'else if'.
print ("That's too few events! Try Again.")
else:
# no need to use Flag, just use break when you want to leave a loop.
break
return n_events
def get_events_names(n_events):
print ("Please enter the events names")
events = []
for n in range(1, n_events + 1):
# starting at 1 to give a better display
event_name = input("Event %i name: " % n)
events.append(event_name)
return events
def get_data(events):
data = []
while True:
house_name = input("Please enter house names <<<Enter XXX when finished>>> :")
if house_name.upper() == "XXX":
# using .upper() to avoid checking twice for either 'xxx' or 'XXX'.
# I would ask the user for how many houses are there instead, but your choice ;)
break
print ("Please enter the events points in ascending order.")
# not actually need to be in ascending order, you can sort them later if you want.
scores = []
for event_name in events:
# don't use range(len(something)), loops in Python are easy!
score = get_score(house_name, event_name)
scores.append([event_name, score])
data.append([house_name, scores])
# use .append() instead of data = data + [...]
return data
def main():
print("Welcome!\n")
n_events = get_number_of_events()
events_names = get_events_names(n_events)
print()
data = get_data(events_names)
print()
for house_name, event_data in data:
print ("House " + house_name)
for event_name, score in event_data:
# note the use of tuple unpacking
print ("\tEvent: %s Score: %i" % (event_name, score))
if __name__ == '__main__':
main()
这次保持与程序相同的结构。
检查评论以获取一些提示和技巧。
另外,尝试保持变量名称的含义,并检查PEP 8的命名约定准则(变量和函数应该是snake_case,
输出:
Welcome!
Please enter the number of events there is.
>>2
Please enter the events names
Event 1 name: Quidditch Match
Event 2 name: Duels
Please enter house names <<<Enter XXX when finished>>> :Gryffindor
Please enter the events points in ascending order.
Please enter score for Gryffindor in the event Quidditch Match:100
Please enter score for Gryffindor in the event Duels:30
Please enter house names <<<Enter XXX when finished>>> :Slytherin
Please enter the events points in ascending order.
Please enter score for Slytherin in the event Quidditch Match:40
Please enter score for Slytherin in the event Duels:50
Please enter house names <<<Enter XXX when finished>>> :XXX
House Gryffindor
Event: Quidditch Match Score: 100
Event: Duels Score: 30
House Slytherin
Event: Quidditch Match Score: 40
Event: Duels Score: 50