gpt4 book ai didi

python - python中列表推导或生成器表达式的续行

转载 作者:IT老高 更新时间:2023-10-28 21:08:03 26 4
gpt4 key购买 nike

你应该如何分解一个很长的列表理解?

[something_that_is_pretty_long for something_that_is_pretty_long in somethings_that_are_pretty_long]

我还曾在某处看到人们不喜欢使用“\”来分行,但一直不明白为什么。这背后的原因是什么?

最佳答案

[x
for
x
in
(1,2,3)
]

工作正常,所以你可以随心所欲。我个人更喜欢

 [something_that_is_pretty_long
for something_that_is_pretty_long
in somethings_that_are_pretty_long]

\ 不受欢迎的原因是它出现在一行的 end 处,它要么不突出,要么需要额外的填充,当行长改变时必须固定:

x = very_long_term                     \
+ even_longer_term_than_the_previous \
+ a_third_term

在这种情况下,请使用括号:

x = (very_long_term
+ even_longer_term_than_the_previous
+ a_third_term)

关于python - python中列表推导或生成器表达式的续行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5809059/

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