如果满足条件

发布于 2025-02-05 09:20:36 字数 513 浏览 2 评论 0原文

我有以下python代码:

for i in range(large_number):
  # compute a_i
  if a_i is condition:
    # Need to make change here for the file open
    f = open('file.log', wb)
    # more computations proceeding. Cannot use break

现在,由于我的代码复杂性,我只能通过

needs_fopen = False
for i in range(large_number):
  # compute a_i
  if a_i is condition:
    needs_fopen = True

if needs_fopen is True:
  f = open('file.log', wb)

我不想执行第二种方法才能实现打开文件。如何实现第一个方法,但只有满足条件时才打开文件一次?

I have the following Python code:

for i in range(large_number):
  # compute a_i
  if a_i is condition:
    # Need to make change here for the file open
    f = open('file.log', wb)
    # more computations proceeding. Cannot use break

Now that I can achieve opening file only once by

needs_fopen = False
for i in range(large_number):
  # compute a_i
  if a_i is condition:
    needs_fopen = True

if needs_fopen is True:
  f = open('file.log', wb)

I do not want to do the second approach due to my code complexity. How to achieve the first method but open the file only once if the condition is satisfied?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

jJeQQOZ5 2025-02-12 09:20:36
f = None
for i in range(large_number):
  # comput a_i
  if a_i is condition and not f:
    f = open('file.log', wb)
f = None
for i in range(large_number):
  # comput a_i
  if a_i is condition and not f:
    f = open('file.log', wb)
邮友 2025-02-12 09:20:36

使用任何()具有生成器理解:

if any(i is condition for i in range(number)):
  f = open('file.log', wb)

Use any() with a generator comprehension:

if any(i is condition for i in range(number)):
  f = open('file.log', wb)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文