如何解决python 3.7单行理解
我有一个看起来像这样的代码:
x = ["hello","world","if"]
test = [len(word) for word in x if len(word)>4]
print(test)
在我的原始代码“ len”中有很多复杂的函数,有没有办法只计算一次len? 在传统的for循环中,可以这样完成:
test = []
for word in x:
temp= len(word)
if temp > 4:
test.append(temp)
您能否建议不使用传统的for循环即可达到相同的结果。
谢谢
解决方法
您可以使用:=
运算符(对于Python 3.8 +):
def my_len(s):
# ...other complicated computations...
return len(s)
x = ["hello","world","if"]
test = [l for word in x if (l:=my_len(word))>4]
print(test)
注意:请勿覆盖默认的内置函数,在这种情况下为len()
。其他功能可能取决于它。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。