【问题标题】:How to append items to various lists without iterating from the beginning?如何在不从头开始迭代的情况下将项目附加到各种列表?
【发布时间】:2022-11-16 07:51:35
【问题描述】:

我正在尝试用“mylist”中的项目填充我的变量“test”。如果满足条件 totaltime < 6,则迭代从 mylist[0] 重新开始,因此列表永远不会超过“3”(mylist 中的第二个索引)。但是,我希望如果满足条件,则迭代将继续填充第二个列表。我怎样才能确保我的迭代从中断的地方继续?结果如下:

mylist = [1, 2, 3, 4, 5, 6, 7, 8]
time = [2, 2, 2, 5, 1, 6, 5, 1]

test = [[], [], [], []]

我尝试了以下

mylist = [1, 2, 3, 4, 5, 6, 7, 8]
time = [2, 2, 2, 5, 1, 6, 5, 1]

test = [[], [], [], []]

totaltime = 0

for i in range(len(test)):
    for jobs in range(len(mylist)):
        if totaltime < 6:
            test[i].append(mylist[jobs])
            totaltime += time[jobs]
    totaltime = 0

print(test)

结果:

[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]

[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]

[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]

但是,如上所述,我希望我的迭代不再重新开始。因此,期望的结果应该如下所示:

test = [1, 2, 3], [4,5], [6], [7, 8]

【问题讨论】:

  • 我真的不明白你想要的结果列表的标准。
  • 为什么3包含在test[0]test[1]?为什么 6 不存在?
  • @juanpa.arrivillaga 6 无处可去,因为相应的时间 (6) 不严格小于 6,因此 if 语句的计算结果为 false 并会跳过它。
  • @juanpa.arrivillaga 你混淆了我的列表和时间列表。时间列表是添加到总时间的时间列表,因此 7 和 8(5 和 1)的时间有效。同样 3 被包含两次,我相信预期的输出是 [1, 2, 3], [4, 5], [7, 8]
  • @actuallyatiger 啊,是的,当然。这是有道理的(你描述的输出)

标签: python nested-for-loop


【解决方案1】:

问题是您正在嵌套循环。我认为最简单的方法就是循环一次并在 test 中保留一个索引,您可以在需要时增加它。以下作品:

mylist = [1, 2, 3, 4, 5, 6, 7, 8]
time = [2, 2, 2, 5, 1, 6, 5, 1]


total_time = 0
i = 0
test = [[], [], [], []]
for t, item in zip(time, mylist):
    total_time += t
    test[i].append(item)
    if total_time >= 6:
        i += 1
        total_time = 0

【讨论】:

    【解决方案2】:

    我从功能的角度来看这个问题,并提出了这个不太明显但可能更容易理解的解决方案。更喜欢 juanpa 的启发,但我可能更喜欢我的生产代码。

    def take_while_sum_lt(max_: int):
        def _inner(iterator):
            acc = []
            total = 0
            for idx, val in iterator:
                total += val
                acc.append(idx)
                if total >= max_:
                    yield acc
                    acc = []
                    total = 0
        return _inner
    

    这是一个迭代器,它获取 mylist, time 的 zip 并产生正确的结果。例如:

    # take_while_sum_lt defined as above
    
    mylist = [1, 2, 3, 4, 5, 6, 7, 8]
    time = [2, 2, 2, 5, 1, 6, 5, 1]
    
    # this produces an iterator function that takes while the sum less than 6
    take_while_sum_lt_6 = take_while_sum_lt(6)
    
    result = take_while_sum_lt_6(zip(mylist, time))
    

    【讨论】:

      猜你喜欢
      • 2020-02-04
      • 1970-01-01
      • 1970-01-01
      • 2010-10-16
      • 1970-01-01
      • 1970-01-01
      • 2010-12-29
      • 2017-11-26
      • 2021-02-23
      相关资源
      最近更新 更多