如何用WHILE循环重写此FOR循环

时间:2020-08-03 04:12:10

标签: python

这是我在Python电子书中的练习之一。我只是想知道是否可以使用WHILE代替FOR。 谢谢您的帮助

#要求用户输入正则表达式 #count与正则表达式匹配的行数。

我的代码

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
 {
      using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
      {
            var context = serviceScope.ServiceProvider.GetRequiredService<LibraryContext>();
            context.Database.Migrate();
      }
      ...
  }

4 个答案:

答案 0 :(得分:2)

如果您真的想提高一个级别,请利用True和False总和分别为1和0的事实。这会在一段时间内完全消除显式。

import re
x = input('Enter a regular expression.')
my_regex = '\\b' + x + '\\b'
with  open('mbox-short.txt') as f:
    count = sum(bool(re.search(my_regex, line)) for line in f)

答案 1 :(得分:1)

您可以使用以下while循环执行与以下相同的任务,

import re
x = input('Enter a regular expression.')
fileHandler = open('tmp.txt')
count = 0
while True:
    line = fileHandler.readline()
    if not line:
        break
    if re.search('\\b' + x + '\\b', line):
        count += 1
print (count)

答案 2 :(得分:0)

x= input('Enter a regular expression.')
file = open('mbox-short.txt') 
count = 0
while(re.search('\\b' + x + '\\b', line)):
   count = count+1
print(count)

我认为这会起作用。

答案 3 :(得分:0)

尝试

x= input('Enter a regular expression.')
file = open('mbox-short.txt') 
count = 0
temp=0
lines=file.readlines()
while True:
    if re.search('\\b' + x + '\\b', lines[temp]):
        count=count+1
    if temp==len(lines)-1:
        break
    temp=temp+1
print(count)
相关问题