gpt4 book ai didi

python - 如何使用列表理解来扩展 python 中的列表?

转载 作者:太空狗 更新时间:2023-10-29 17:17:05 25 4
gpt4 key购买 nike

<分区>

我没有使用 Python 的经验,我经常编写(简化)如下所示的代码:

accumulationList = []
for x in originalList:
y = doSomething(x)
accumulationList.append(y)
return accumulationList

然后在我的测试通过后,我重构为

return [doSomething(x) for x in originalList]

但假设结果有点不同,我的循环看起来像这样:

accumulationList = []
for x in originalList:
y = doSomething(x)
accumulationList.extend(y)
return accumulationList

doSomething 列表返回一个列表。完成此任务的最 Pythonic 方法是什么?显然,之前的列表理解会给出列表的列表。

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