我正在尝试使用Python 3编写python程序
我必须打开一个文本文件并读取一个名称列表,打印列表,按字母顺序对列表进行排序,然后最后重新打印列表。 还有一点比这更多但是我遇到的问题是我应该在一个单独的行上打印每个名字的名单列表
不是在单独的行上打印每个名称,而是在一行上打印所有列表。 我该如何解决这个问题?
def main():
#create control loop
keep_going = 'y'
#Open name file
name_file = open('names.txt', 'r')
names = name_file.readlines()
name_file.close()
#Open outfile
outfile = open('sorted_names.txt', 'w')
index = 0
while index < len(names):
names[index] = names[index].rstrip('\n')
index += 1
#sort names
print('original order:', names)
names.sort()
print('sorted order:', names)
#write names to outfile
for item in names:
outfile.write(item + '\n')
#close outfile
outfile.close()
#search names
while keep_going == 'y' or keep_going == 'Y':
search = input('Enter a name to search: ')
if search in names:
print(search, 'was found in the list.')
keep_going = input('Would you like to do another search Y for yes: ')
else:
print(search, 'was not found.')
keep_going = input('Would you like to do another search Y for yes: ')
main()
答案 0 :(得分:2)
问题在于:print('original order:', names)
。这是在一行中打印所有列表。因此,要在新行中打印列表的每个元素,您必须执行以下操作:
print('original order:')
for name in names:
print(name)
names.sort()
print('sorted order:')
for name in names:
print(name)