扫描项目列表,并返回特定值

时间:2019-06-17 22:34:48

标签: python python-3.x

因此对于我的程序,这是一个媒体实验室,库存有各种书籍和电影。我想要实现许多不同的选项,其中一个我想要并试图实现一个选项,当用户按下2时,程序将返回有关媒体存储的信息。

$shiftInPre = new \DateTime($row["time_start"] /* <-e.g. 8:02*/);
echo roundtoLastQuarterHour($shiftInPre);

这就是我要在功能信息中执行的操作。我用语言表达了我想做的事情,但是有没有办法像循环一样读取/扫描整个列表并找到关于目录的这些内容?我试图创建该功能来打印库存价值,但是它没有起作用。

Inventory is worth $75.89
Most expensive item at $11.99
There are 5 Book(s), and 4 Movie(s)

1 个答案:

答案 0 :(得分:0)

将问题分解成小块。

Inventory is worth $75.89
Most expensive item at $11.99
There are 5 Book(s), and 4 Movie(s)

首先,编写仅计算$75.89行中的Inventory is worth $75.89的代码,下面的函数sum_prices将为我们做到这一点:

def sum_prices(all_items):
    count = 0
    for item in all_items:
        count = count + item.price
    return count

我们可以如下测试sum_prices

full_catalog  = initialize()
inventory_value = sum_prices(full_catalog)
print(inventory_value)

它打印75.89。很好接下来,让我们写一些代码,找出最昂贵的价格。

def get_highest_price(all_items):
    high_price = float("-inf")
    for item in all_items:
        if high_price < item.price:
            high_price = item.price
    return high_price

下面是一些测试get_highest_price

的代码
full_catalog = initialize()
hp = get_highest_price(full_catalog)
print(hp)

上面的代码显示11.99,这似乎是最高价。

我们还可以计算图书数量和电影数量:

def count_media_type(all_items, media_type):
    count = 0
    for item in all_items:
        if item.media == media_type:
            count += 1
    return count

def count_books(all_items):
    return count_media_type(all_items, "Book")

def count_movie(all_items):
    return count_media_type(all_items, "Movie")

在您解开了拼图的所有小片段之后,可以将它们放在一起:

def print_stats(all_items):
    inv_value = sum_prices(all_items)
    high_price = get_highest_price(all_items)
    book_count = count_books(all_items)
    movie_count = count_movie(all_items)

    print("Inventory is worth $", inv_value)
    print("Most expensive item at $", high_price)
    print("There are", book_count, "Book(s) and", movie_count, "Movie(s)")