gpt4 book ai didi

Python while 和 for 循环 - 我可以使代码更高效吗?

转载 作者:太空宇宙 更新时间:2023-11-04 10:41:58 25 4
gpt4 key购买 nike

我写了下面的代码:

initial_list = [item1, item2, item3, item4, ...]
lists = [[list1], [list2], [list3], [list4], ..., [list(n-1)], [list(n)]]
# The number of elements in the both lists might chance

while len(initial_list) > 0:
for list in lists:
if len(initial_list) == 0:
break
item = initial_list.pop(0)
list.append(item)

我想知道是否有更好/更简单/更短的方式来编写上面的代码?如果是,请不要使用困难的功能(等),因为我还是初学者,不会理解它。

最佳答案

我相信您正在尝试将 initial_list 中的项目附加到 lists 中的嵌套列表值,直到所有值 initial_list 都被使用,循环lists 如果嵌套列表少于要附加的初始值,则从头开始。

使用zip()将嵌套列表与 initial_list 项配对:

from itertools import cycle

for nested, value in zip(cycle(lists), initial_list):
nested.append(value)

itertools.cycle() function这里确保使用 initial_list 中的所有值; zip()最短 列表处停止,此处始终为initial_lists

具有 10 个值(整数 09)的初始列表和具有 4 个空子列表的嵌套列表的演示:

>>> from itertools import cycle
>>> initial_list = range(10)
>>> lists = [[] for _ in range(4)]
>>> for nested, value in zip(cycle(lists), initial_list):
... nested.append(value)
...
>>> lists
[[0, 4, 8], [1, 5, 9], [2, 6], [3, 7]]

不使用循环将要求您保留一个计数器并附加到 lists[count % len(lists)]。可以使用 enumerate() 函数生成计数器:

for i, value in enumerate(initial_list):
lists[i % len(lists)].append(value)

关于Python while 和 for 循环 - 我可以使代码更高效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20079659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com