【问题标题】:Nested for loop not running in python after the first iteration [duplicate]第一次迭代后嵌套的for循环没有在python中运行[重复]
【发布时间】:2021-10-14 12:54:55
【问题描述】:

我有一个嵌套的 for 循环,在第一次迭代后没有运行

N, M = map(int, input().split())
numbers = map(int, input().split())

dic = {}
for m in range(N):
  dic.setdefault(m,[])
  for n in numbers:
      if n % N == m:
      dic[m].append(n)
print(dic)

上面的代码正在为下面的示例数据生成以下结果{0: [3, 42], 1: [], 2: []}

3 5
1 3 8 10 42

但是我想得到{0: [3, 42], 1: [1, 10], 2: [8]} 我做错了什么?

【问题讨论】:

    标签: python list dictionary for-loop nested-loops


    【解决方案1】:

    问题在于map 返回一个迭代器,而您在第一个外循环中完全使用了迭代器。你需要:

    numbers = [int(k) for k in input().split()]
    

    而不是使用map

    【讨论】:

    • numbers = list(map(int, input().split())),其中list 内置函数将迭代器转换为列表(尽管蒂姆的回答更符合pythonic)。
    • 只是为了提供替代方案,numbers = [*map(int, input().split())] 也可以。
    • 这是一场有趣的辩论。我更喜欢 map 调用的外观,但我已经像 OP 一样被烧毁了,所以我通常避免使用它,而支持列表理解。
    【解决方案2】:

    试试这个:

    N, M = map(int, input().split())
    numbers = [int(x) for x in input().split()]
    
    dic = {}
    for m in range(N):
        dic.setdefault(m,[])
        for n in numbers:
            print(n % N)
            if n % N == m:
                dic[m].append(n)
    print(dic)
    

    【讨论】:

    • 这正是我所说的。
    • 是的..我发布我的答案时没有看到你的答案.. :)
    猜你喜欢
    • 2019-12-19
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多