如何创建过滤列中指定条件的函数?

2024-06-28 19:37:00 发布

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

这是我的数据集

我的任务是编写一个函数,过滤掉超过某个值的电影。 函数应该有两个输入参数:表和指定的运行时间。在一个新的表格中,我只能包括两小时或更短的电影,并按票房总额降序排列。然后我需要在屏幕上打印返回表的前5个元素

这是我到目前为止所拥有的,但我正在使用的程序说有错误-“创建函数filter\u not\u longer\u than()

    ["Driving Miss Daisy", 1989, 7.645, 99, ['drama'], 7.5, 145.793296],
    ["Rain Man", 1988, 8.25, 133, ['drama'], 25.0, 354.825435],]


def filter_not_longer_than(data, length_threshold):
    result = []
    for row in data:
        length = row[3]
        if length <= length_threshold:
            result.append(row)
    return result

def print_top5_by_column(data, column, reverse):
    data.sort(key=lambda row: row[column], reverse=reverse)
    print('Title                            | Year  | Rating | Length | Budget | Box office gross  |')
    print('--------------------------------------------------------------------------------')
    for row in data[:5]:
        print('{: <35} | {} | {: >7.2f} | {: >5} | {: >6.1f} | {: >6.1f} |'.format(
            row[0], row[1], row[2], row[3], row[5], row[6]))

filter_not_longer_than = filter_not_longer_than(oscar_data, 120)
print_top5_by_column(filter_not_longer_than, 6, True)

Tags: 函数data电影defnotcolumnresultfilter
1条回答
网友
1楼 · 发布于 2024-06-28 19:37:00
parallels$ python  version
Python 3.7.3

你的代码非常适合我。在此复制:

oscar_data = [["Driving Miss Daisy", 1989, 7.645, 99, ['drama'], 7.5, 145.793296],
                ["Rain Man", 1988, 8.25, 133, ['drama'], 25.0, 354.825435],]

def filter_not_longer_than(data, length_threshold):
    result = []
    for row in data:
        length = row[3]
        if length <= length_threshold:
            result.append(row)
    return result

def print_top5_by_column(data, column, reverse):
    data.sort(key=lambda row: row[column], reverse=reverse)
    print('Title                            | Year  | Rating | Length | Budget | Box office gross  |')
    print('                                        ')
    for row in data[:5]:
        print('{: <35} | {} | {: >7.2f} | {: >5} | {: >6.1f} | {: >6.1f} |'.format(
            row[0], row[1], row[2], row[3], row[5], row[6]))

filter_not_longer_than = filter_not_longer_than(oscar_data, 120)
print_top5_by_column(filter_not_longer_than, 6, True)
parallels$ python so.py 
Title                            | Year  | Rating | Length | Budget | Box office gross  |
                                        
Driving Miss Daisy                  | 1989 |    7.64 |    99 |    7.5 |  145.8 |

如果你仍然得到任何错误,做评论,并将很高兴一起调试

相关问题 更多 >