gpt4 book ai didi

python - 如何用Python编写过滤函数

转载 作者:行者123 更新时间:2023-12-01 06:47:59 27 4
gpt4 key购买 nike

我有以下格式的足球比赛列表:

# HomeTeam, AwayTeam, HomeScore, AwayScore, HomeShots, AwayShots
[['Bayer 04', 'Werder Bremen', 2, 2, 21, 10]
['Paderborn', 'RB Leipzig', 2, 3, 8, 18]
['Koln', 'Augsburg', 1, 1, 13, 11]]

假设我只想提取那些满足某些条件的匹配项,例如:

  • 主队是“Bayer 04”,主场射门 + 客场射门 > 25
  • AwayTeam 是以下球队之一:“RB Leipzig”或“Koln”
  • 客场进球 > 主场进球

虽然按单个标准过滤列表很简单,例如提取进球数超过 3 个的比赛:

def moreThan3Goals(matches):
result = []
[result.append(match) for match in matches if match[2] + match[3] > 3]
return result

目前尚不清楚如何编写一个接受任意数量的条件并提取满足所有条件的匹配的函数。

最佳答案

您可能需要考虑使用namedtuple来使函数可读。

from collections import namedtuple

# Convert raw data to list of named tuples.
col_names = ['HomeTeam', 'AwayTeam', 'HomeScore', 'AwayScore', 'HomeShots', 'AwayShots']
Match = namedtuple('Match', col_names)
raw_data = [
['Bayer 04', 'Werder Bremen', 2, 2, 21, 10],
['Paderborn', 'RB Leipzig', 2, 3, 8, 18],
['Koln', 'Augsburg', 1, 1, 13, 11]
]
data = [Match(*m) for m in raw_data]
>>> data
[Match(HomeTeam='Bayer 04', AwayTeam='Werder Bremen', HomeScore=2, AwayScore=2, HomeShots=21, AwayShots=10),
Match(HomeTeam='Paderborn', AwayTeam='RB Leipzig', HomeScore=2, AwayScore=3, HomeShots=8, AwayShots=18),
Match(HomeTeam='Koln', AwayTeam='Augsburg', HomeScore=1, AwayScore=1, HomeShots=13, AwayShots=11)]

然后使用 lambda 函数创建任意规则:

rule_1 = lambda m: m.HomeTeam == 'Bayer 04' and (m.HomeShots + m.AwayShots) > 25
rule_2 = lambda m: m.AwayTeam in {'RB Leipzig', 'Koln'}
rule_3 = lambda m: m.AwayScore > m.HomeScore

现在您可以使用条件列表理解来匹配所有规则,将命名元组转换回列表:

[list(m) for m in data 
if all([rule_1(m), rule_2(m), rule_3(m)])]

或者通过创建规则组:

rule_set_1 = [rule_1, rule_2, rule_3]
[list(m) for m in data
if all([rule(m) for rule in rule_set_1])]

关于python - 如何用Python编写过滤函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59145388/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com