【问题标题】:Using list of queues in a list使用列表中的队列列表
【发布时间】:2022-12-20 05:11:55
【问题描述】:
    num_of_stacks = int((len(config[0]) + 1)/4)
    stacks = [Queue() for i in range(num_of_stacks)]
    # stacks = list(map(Queue, range(num_of_stacks)))
    print(stacks)
    for line in config[len(config)-2::-1]:
        print(stacks)
        for i in range(0, len(line), 4):
            print(int(i/4), line[i+1: i+2])
            if line[i+1: i+2] != ' ':
                print(stacks[int(i/4)])
                stacks[int(i/4)].put(line[i+1: i+2])
        print(line)

我正在编写一个程序来解决最新的 Advent of Code 挑战。

试图创建这样的队列列表:

stacks = list(map(Queue, range(num_of_stacks)))

在遍历它时,我的整个程序都冻结了。另一方面,使用列表理解创建队列列表解决了这个问题:

stacks = [Queue() for i in range(num_of_stacks)]

输入示例:

                [M]     [W] [M]    
            [L] [Q] [S] [C] [R]    
            [Q] [F] [F] [T] [N] [S]
    [N]     [V] [V] [H] [L] [J] [D]
    [D] [D] [W] [P] [G] [R] [D] [F]
[T] [T] [M] [G] [G] [Q] [N] [W] [L]
[Z] [H] [F] [J] [D] [Z] [S] [H] [Q]
[B] [V] [B] [T] [W] [V] [Z] [Z] [M]
 1   2   3   4   5   6   7   8   9 

有谁能解释为什么在调试时返回相同对象的两个代码在将数据放入队列时的工作方式不同?

【问题讨论】:

    标签: python list queue list-comprehension


    【解决方案1】:

    这两个表达式不等价:

    stacks = list(map(Queue, range(num_of_stacks)))
    stacks = [Queue() for i in range(num_of_stacks)]
    

    因为map调用函数与可迭代的元素作为论据。因此,对您的 map 调用的等效列表理解将是:

    stacks = [Queue(i) for i in range(num_of_stacks)]
    

    您没有为您的 Queue 类提供代码,但我推断当您将参数传递给它的构造函数时它会做一些不好的事情。

    【讨论】:

    • 旁白:这个例子很好地说明了为什么使用生成器表达式或列表推导式通常比 map 更受欢迎——在列表推导式中更容易看到实际执行的内容,而不必在脑海中想象 @987654327 的效果@ 称呼!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-17
    • 1970-01-01
    • 2010-11-20
    • 2011-11-14
    相关资源
    最近更新 更多