我有以下格式的足球比赛列表:
# 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]]
假设我只想提取满足某些条件的那些匹配项,例如:
虽然按单个条件过滤列表很简单,例如提取得分超过3个目标的比赛:
def moreThan3Goals(matches):
result = []
[result.append(match) for match in matches if match[2] + match[3] > 3]
return result
尚不清楚如何编写具有任意数量条件的函数并提取满足所有条件的匹配项。
答案 0 :(得分:1)
您可能要考虑使用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])]