Navigation

    GitHub中文社区
    • GitHub排行榜

    论坛

    • Login
    • Categories
    • Recent
    • Tags
    • Popular

    Python新手请教 - 数7游戏

    技术交流
    2
    3
    717
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • cyonsoft
      cyonsoft last edited by

      '''
      我是Python小白 小影子,很高兴认识各位前辈。
      最近我学到推导式,想结合列表推导式编一个数7游戏,目标是在指定列出所有不含7数字和倍数的数字。
      '''

      list1 = [i1 for i1 in range(0,81) if i1 % 7 != 0]

      for i2 in list1:
      CheckNum = str(i2)
      if CheckNum.find('7') != -1:
      list1.remove(int(CheckNum))
      print(list1)

      #但是程序会跳出[72, 74, 76, 79], 我不知道问题出在哪里。请前辈们指教。

      1 Reply Last reply Reply Quote 0
      • k1995
        k1995 last edited by

        我改了下代码,第二行 for i2 in list1 变成了 for i2 in list1.copy()。就没问题了

        list1 = [i1 for i1 in range(0,81) if i1 % 7 != 0]
        for i2 in list1.copy():
            CheckNum = str(i2)
            if CheckNum.find('7') != -1:
                list1.remove(int(CheckNum))
        print(list1)
        
        k1995 1 Reply Last reply Reply Quote 1
        • k1995
          k1995 @k1995 last edited by k1995

          这个是因为在for循环中,如果你删除列表中一个元素,列表的结构发生了变化。后面的元素向前移,元素的索引发生变化,但你依然按照原来的索引进行遍历,就会有漏网之鱼,所以就出现了你说的这个问题。

          这是Python的一个坑,详情可以参考
          https://blog.csdn.net/weixin_44520259/article/details/89640114
          https://blog.csdn.net/weixin_45912291/article/details/108813240
          Java中这种对列表这么操作会直接报错,叫fail-fast

          1 Reply Last reply Reply Quote 0
          • First post
            Last post