我正在写一个程序,其中包含一个包含四位美国总统名字的列表。使用任何你想要的总统。然后,运行一个循环,将另外四位总统添加到列表中。使用列表作为其唯一参数调用另一个函数。第二个函数应该对列表进行排序,然后循环遍历列表,以便在自己的行上打印每个总统的名字。我完成了一些代码,但它只打印第一组名称的列表。我想不出如何对名单中输入的名字进行排序并打印出所有的名字。
下面是我的代码:
president = 4
def main():
names = [0] * president
for pres in range(president):
print('Enter the name of a president',sep='',end='')
names[pres] = input()
names.sort()
print(names)
for pres in range(president):
print('Enter the name of another president',sep='',end='')
names[pres] = input()
def names(name_list):
name_list.sort()
return name_list发布于 2017-02-28 09:53:26
变量'pres‘在第二个循环的第17行被重置(它将遍历索引0-3并覆盖之前的4个主席)。为了快速解决问题,可以同时尝试第17行的names[pres + 4] = input()和第6行的names = [""] * 8
发布于 2017-02-28 12:13:28
for pres in range(president):
print('Enter the name of a president',sep='',end='')
names[pres] = input()
names.sort()
print(names)您不需要在每次添加新总裁时都执行names.sort()。如果你想添加4个总裁,那就添加它。排序是最后一步,对吧?
在第二个循环中,使用相同的索引添加另一个总裁。这将改变你列表中的元素,你仍然只有4个总裁,不会更多。我的建议是使用
new_president = input()
names.append(new_president)而不是
names[pres] = input()下面是我的完整代码:
def create_presidents(no_presidents=4):
presidents = []
for _ in range(no_presidents):
presidents.append(input("Enter a name: "))
# More presidents
for _ in range(no_presidents):
presidents.append(input("Enter another name: "))
presidents.sort()
return presidents
def print_presidents(presidents):
for president in presidents:
print(president)
if __name__ == "__main__":
no_presidents = 4
presidents = create_presidents(no_presidents)
print_presidents(presidents) 发布于 2017-03-01 15:38:57
我甚至比我刚开始的时候更困惑:Huy vo,我认为默认情况下,4个总统的名字应该在列表中,然后用户激励并添加4个其他的人到该列表中,然后它应该显示该列表。
https://stackoverflow.com/questions/42498731
复制相似问题