【问题标题】:What's wrong with my for loop? Python我的 for 循环有什么问题? Python
【发布时间】:2016-05-05 21:10:22
【问题描述】:

这个 for 循环应该在我的输入中迭代甚至“行”,因为它包含我想放在字典中作为键的用户名,并且该键内有一个字典。我的输出确实包括我需要的信息,但也包括我不想要的奇怪行。 我是 python 新手,所以我仍在尝试理解语法。 这是我的代码:

def get_name(string_input):
    split_fullstop = string_input.split('.')
    list = [] #creates a list                               
    for line in split_fullstop: 
        count = 0   
        if count % 2 == 0: #if count is even            
            list.append(line.split('is connected to')) #add info to 'list'      
            count += 1 #increase count
        names = {name[0]:{} for name in list}
    return names

这是打印函数后的输出:

{'': {}, 'Levi ': {}, 'Bryant ': {}, 'Jennie likes to play Super Mushroom Man, Dinosaur Diner, Call of Arms': {}, 'Olive likes to play The Legend of Corgi, Starfleet Commander': {}, 'Debra likes to play Seven Schemers, Pirates in Java Island, Dwarves and Swords': {}, 'Levi likes to play The Legend of Corgi, Seven Schemers, City Comptroller: The Fiscal Dilemma': {}, 'Walter ': {}, 'Robin ': {}, 'John ': {}, 'Walter likes to play Seahorse Adventures, Ninja Hamsters, Super Mushroom Man': {}, 'Debra ': {}, 'Freda likes to play Starfleet Commander, Ninja Hamsters, Seahorse Adventures': {}, 'Mercedes likes to play The Legend of Corgi, Pirates in Java Island, Seahorse Adventures': {}, 'Ollie ': {}, 'Robin likes to play Call of Arms, Dwarves and Swords': {}, 'Bryant likes to play City Comptroller: The Fiscal Dilemma, Super Mushroom Man': {}, 'Freda ': {}, 'Olive ': {}, 'Mercedes ': {}, 'John likes to play The Movie: The Game, The Legend of Corgi, Dinosaur Diner': {}, 'Jennie ': {}, 'Ollie likes to play Call of Arms, Dwarves and Swords, The Movie: The Game': {}}

【问题讨论】:

  • @AntonProtopopov 你应该提到它作为答案,点赞!!
  • 你还没有写出输入是什么,也没有写出预期的输出是什么。

标签: python list for-loop dictionary


【解决方案1】:

请记住,for 循环下方相同缩进级别的所有代码将在每次迭代中运行。因此,您要在 for 循环经过的每个项目中重新定义变量 countnames。如其中一个 cmets 所述,names 应与return 语句处于相同的缩进级别。

在每次迭代中重新定义count 意味着您将始终找到0 % 2 == 0。它应该在 for 循环之前定义。此外,您仅在运行 #if count is even 部分时增加 count。因此,假设count 在循环之前定义,您将看到0 为偶数,增加count 并永远留下1 的奇数值。

看看使用enumerate 同时循环索引和值。这样你只需要检查索引的偶/奇值。

【讨论】:

    【解决方案2】:

    也许您的计数是错误缩进,计数旨在过滤偶数行。

    for line in split_fullstop: 
        count = 0   
        if count % 2 == 0: #if count is even            
            list.append(line.split('is connected to')) #add info to 'list'      
        count += 1 #increase count
    

    【讨论】:

      【解决方案3】:

      因此,您使用了“for each 循环”,它循环遍历可迭代和内置功能中的每个元素,以仅评估偶数索引。与其这样,我认为使用函数范围更清晰干净。

      range(0, len(split_fullstop), 2)
      

      只计算偶数

      【讨论】:

        【解决方案4】:

        我将只关注您的 count 变量,因为这是告诉我有错误的第一件事:

        for line in split_fullstop: 
            count = 0   
            if count % 2 == 0: #if count is even            
                # some code
            count += 1 #increase count
            #some code
        return names
        

        首先,您将在每个循环上重置count 变量,并在循环内使用count = 0,因此每个循环count%2 将等于0。这条线应该在循环之外(之前)。

        第二,你在if条件count%2 == 0中增加变量,如果在一次迭代中count == 0,那么它将进入if部分,并将值增加到count == 1
        在下一次(以及所有其他)迭代中,由于 count == 1,if 部分的内部不会被执行,因此 count 变量不会改变。

        所以,应该是这样的:

        count = 0   
        for line in split_fullstop: 
            if count % 2 == 0: #if count is even            
                #some code
                count += 1 #increase count
        return names
        

        【讨论】:

          【解决方案5】:

          注意:不要使用诸如list 之类的内置变量,因为您会覆盖它们,并可能导致将来出现意外行为。以l 为例。

          带有names = {name[0]:{} for name in list} 的行将在每一步都执行,因为它与if 语句的位置不同。对于count % 2 == 1 的步骤,您将添加到dict 空列表中。但是在您的解决方案中,您在每个步骤中都重新定义了count,因此您永远不会像@Isaac Drachman 提到的那样得到它。所以只需删除一些空格或制表符并在for循环之前定义count

          def get_name(string_input):
              split_fullstop = string_input.split('.')
              l = [] #creates a list            
              count = 0                      
              for line in split_fullstop: 
                  if count % 2 == 0: #if count is even            
                      l.append(line.split('is connected to')) #add info to 'list'      
                      count += 1 #increase count
              names = {name[0]:{} for name in l}
              return names
          

          或者你可以用list comprehensionenumerate重写它:

          def get_name(string_input):
              l = [line.split('is connected to') for i, line in enumerate(string_input.split('.')) if i % 2 == 0]
              names = {name[0]:{} for name in l}
              return names
          

          【讨论】:

          • names = ... 行看起来像是打算在 for 循环构建的 list 结束时运行一次。因此,它看起来需要取消缩进一个级别,而不是缩进另一个级别。
          猜你喜欢
          • 2011-04-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-03-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多