gpt4 book ai didi

python - 表达方式在 Python 中组合生成器

转载 作者:太空狗 更新时间:2023-10-30 01:04:55 25 4
gpt4 key购买 nike

我真的很喜欢 Python 生成器。特别是,我发现它们是连接到 Rest 端点的正确工具——我的客户端代码只需要在连接到端点的生成器上进行迭代。但是,我发现 Python 生成器的表现力不如我希望的一个领域。通常,我需要过滤从端点获取的数据。在我当前的代码中,我将谓词函数传递给生成器,它将谓词应用于它正在处理的数据,并且仅在谓词为真时才生成数据。

我想转向生成器的组合——比如data_filter(datasource( ))。这是一些演示代码,展示了我的尝试。很明显为什么它不起作用,我想弄清楚的是什么是达成解决方案的最具表现力的方式:

# Mock of Rest Endpoint: In actual code, generator is 
# connected to a Rest endpoint which returns dictionary(from JSON).
def mock_datasource ():
mock_data = ["sanctuary", "movement", "liberty", "seminar",
"formula","short-circuit", "generate", "comedy"]
for d in mock_data:
yield d

# Mock of a filter: simplification, in reality I am filtering on some
# aspect of the data, like data['type'] == "external"
def data_filter (d):
if len(d) < 8:
yield d

# First Try:
# for w in data_filter(mock_datasource()):
# print(w)
# >> TypeError: object of type 'generator' has no len()

# Second Try
# for w in (data_filter(d) for d in mock_datasource()):
# print(w)
# I don't get words out,
# rather <generator object data_filter at 0x101106a40>

# Using a predicate to filter works, but is not the expressive
# composition I am after
for w in (d for d in mock_datasource() if len(d) < 8):
print(w)

最佳答案

data_filter 应将 len 应用于 delements 而不是 d本身,像这样:

def data_filter (d):
for x in d:
if len(x) < 8:
yield x

现在你的代码:

for w in data_filter(mock_datasource()):
print(w)

返回

liberty
seminar
formula
comedy

关于python - 表达方式在 Python 中组合生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48232573/

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