修复嵌套For循环

2024-04-18 19:48:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些麻烦得到一些嵌套的'for循环'的工作方式,我需要他们。我一直在寻找一个答案,这种情况似乎经常发生,但由于我对Python还是相当陌生,所以这些解释并没有太大帮助。我有一个单词列表,和一个文件,我正在使用,并希望列表中的每个单词逐行检查文件,如果该行包含单词,则打印该行。当前,当我运行代码时,它只打印出包含列表中第一个单词的行,而不会继续打印列表中其余的单词。你知道吗

你能不能给我一些建议,让我如何能使这项工作?你知道吗

注意:我知道“效率”拼写错误,这是数据源的问题。你知道吗

编辑:我需要对行进行分组,所以所有包含“速度”的行都要打印,然后所有包含“加速度”的行都要打印等等。文件中的所有行都包含一个单词。你知道吗

SHEETS = [' Speed',' Acceleration',' Engine Power',' Instantaneous Fuel Effeciency',
          ' Average Fuel Effeciency',' Instantaneous MPG',' Average MPG',
          ' MAF air flow rate',' Accelerator pedal position E',
          ' Commanded throttle actuator']


with open('userdata.log','r',encoding = 'utf-8') as my_file:
    for label in SHEETS:
        for line in my_file:
            if label in line:
                print (line)

输出:

2014-09-20 14:08:41.165,速度,0,英里/小时

2014-09-20 14:08:43.742,速度,0,英里/小时

2014-09-20 14:08:47.872,速度,0,英里/小时

2014-09-20 14:08:49.490,速度,0,英里/小时

2014-09-20 14:08:51.007,速度,0,英里/小时

2014-09-20 14:08:52.456,速度,0,英里/小时

2014-09-20 14:08:53.888,速度,0,英里/小时

2014-09-20 14:08:55.499,速度,0,英里/小时

2014-09-20 14:08:57.288,速度,0,英里/小时

2014-09-20 14:08:57.838,速度,0,英里/小时

2014-09-20 14:08:58.355,速度,0,英里/小时

2014-09-20 14:08:58.572,速度,0,英里/小时


Tags: 文件in列表formyline单词速度
3条回答

Python中并不是所有的东西都支持重复迭代。一般来说,iterables有两类:迭代器,您只能迭代一次;多用途iterables,您可以随意迭代多次。文件对象属于第一类。你知道吗

如果获得预期的特定结果顺序很重要,则可以在循环之后将文件位置重置为开头:

with open('userdata.log','r',encoding = 'utf-8') as my_file:
    for label in SHEETS:
        for line in my_file:
            if label in line:
                print (line)
        my_file.seek(0)

您还可以考虑交换循环的顺序,并在最后打印之前将行收集到每个标签的列表中。由于I/O更少,这可能会运行得更快:

labeled_lines = {label: [] for label in SHEETS}
with open('userdata.log','r',encoding = 'utf-8') as my_file:
    for line in my_file:
        for label in SHEETS:
            if label in line:
                labeled_lines[label].append(line)
                break
        else:
            # else on a loop means "if the loop didn't end with a break."
            raise SomeAppropriateException
for label in SHEETS:
    for lines in labeled_lines[label]:
        print(line)

最后,您将从文件中读取的行的末尾通常会有换行符。(唯一可能的例外是文件的最后一行。)由于print添加了自己的换行符,这将导致输出的每一行后面都有一个空行。您可能希望剥离换行符以避免这种情况。你知道吗

我想你的意思是:

 SHEETS = [' Speed',' Acceleration',' Engine Power',' Instantaneous Fuel Effeciency',
      ' Average Fuel Effeciency',' Instantaneous MPG',' Average MPG',
      ' MAF air flow rate',' Accelerator pedal position E',
      ' Commanded throttle actuator']


with open('userdata.log','r',encoding = 'utf-8') as my_file:
     for line in my_file:
         for label in SHEETS:
            if label in line:
                print (line)

嵌套循环从外到内:对于文件中的每一行,检查该行中是否存在任何标签。你知道吗

这是因为此循环第一次运行时:

for label in SHEETS:
    for line in my_file:

它遍历整个文件,然后停止(它不会“倒带”并从顶部重新开始)。所以它所做的就是提取第一个单词并搜索整个文件。。。因为文件已经被搜索过了(在最后一行是line),所以它找不到其他单词。你知道吗

在您的情况下,最简单的解决方案是切换逻辑:对于文件中的每一行,查看它是否包含任何单词。这样,您可以在每行搜索一次所有单词(而不是整个文件中效率较低的一个单词)。你知道吗

最终的结果是一样的-你将打印任何行,其中包含的话,你是在后面。实现非常简单,只需切换循环的顺序:

with open('userdata.log','r',encoding='utf-8') as my_file:
    for line in my_file:
        for label in SHEETS:
            if label in line:
                print(line)

I need the lines to be grouped, so all the lines containing 'Speed' printed, then all the lines containing 'Acceleration' printed etc. All the lines in the file contain one of the words in SHEETS.

啊,这是另一回事。为此,您需要使用字典,它是Python的键/值存储容器。你知道吗

字典是一个地方,你可以存储或分组的东西,并参考他们的关键。你知道吗

在您的情况下,您希望将所有与单词匹配的行组合在一起,因此您的关键字将是单词,而内容将是一组行。在字典中,每个键都有一个列表作为值(列表是许多容器类型中的一种,另一种是元组)。你知道吗

lines_by_word = {}  # This is how you create an empty dictionary
with open('userdata.log', 'r', encoding='utf-8') as my_file:
   for line in my_file:
      for label in SHEETS:
          if label in line:
              # Now we have a match - next step is to
              # collect it. However, if this is the first time
              # we have encountered this word, we need to add it
              # to the dictionary
              if label not in lines_by_word:
                 # By default, dictionary return
                 # their keys in a "in" test (called a membership test)
                 # if the word doesn't exist, we need to create a blank
                 # list for it and add it to the dictionary
                 lines_by_word[label] = []

              lines_by_word[label].append(line) # Simply add the matching line
                                                # to the list for that word

for word,lines in lines_by_word.iteritems():
    print('There are total of {} lines for {}'.format(word, len(lines))
    for line in line:
        print(line)

相关问题 更多 >