程序应该询问每种水果有多少磅。然后,程序应以水果的形式显示信息,重量按字母顺序列出,每行一种水果类型,如下所示, 苹果,6磅。 香蕉,11磅。 我以这种方式编写了代码,但我不知道如何按问题所示进行排序和显示:
fruit_list = []
empty_str = ''
print('Enter type of fruit, and how many pounds of each type there are')
print('(hit return when done)\n')
entered_fruit = input('Enter fruit: ')
while entered_fruit != empty_str:
num_pounds = int(input('Enter number of pounds of ' + entered_fruit + ': '))
if len(fruit_list) == 0:
fruit_list = [(entered_fruit, num_pounds)]
else:
insert_index = 0
index = 0
location_found = False
while index < len(fruit_list) and not location_found:
if fruit_list[index][0] < entered_fruit:
index = index + 1
else:
fruit_list.insert(index,(entered_fruit, num_pounds))
location_found = True
entered_fruit = input('\nEnter fruit: ')
print("the fruit List: ", fruit_list)
你能看一下我的密码让我知道有什么问题吗
谢谢大家
一个循环就足够了:
输出:
使用
itemgetter
。示例:itemgetter(0)
将获得第一个项目,即水果名称,这样您就可以按字母顺序对列表进行排序输出:
相关问题 更多 >
编程相关推荐