简单Python代码中排序的一些问题

2024-10-02 04:26:43 发布

您现在位置:Python中文网/ 问答频道 /正文

程序应该询问每种水果有多少磅。然后,程序应以水果的形式显示信息,重量按字母顺序列出,每行一种水果类型,如下所示, 苹果,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)

你能看一下我的密码让我知道有什么问题吗

谢谢大家


Tags: of程序inputindexlocationnumlistempty
2条回答

一个循环就足够了:

fruits = []
while True:
    fruit = input('Input fruit name: ')
    weight = input('Input weight (pounds): ')
    fruits.append('{}, {} lbs'.format(fruit, weight))
    action = input('Do you want to add another fruit [y/n]? ').lower()
    if action == 'n':
        break

print('The fruit list: ')
for fruit in sorted(fruits):
    print(fruit)

输出:

Input fruit name: Banana
Input weight (pounds): 11
Do you want to add another fruit [y/n]? y
Input fruit name: Apple
Input weight (pounds): 6
Do you want to add another fruit [y/n]? n
The fruit list: 
Apple, 6 lbs
Banana, 11 lbs

使用itemgetter。示例:

from operator import itemgetter
fruit_list = [("Banana", 9), ("Peach", 7), ("Apple", 3)]
print(sorted(fruit_list, key=itemgetter(0)))

itemgetter(0)将获得第一个项目,即水果名称,这样您就可以按字母顺序对列表进行排序

输出:

[('Apple', 3), ('Banana', 9), ('Peach', 7)]

相关问题 更多 >

    热门问题