在Python中动态分割列表

2024-04-27 04:28:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个超过5000个项目的清单,这个数字可以每天变化(可以上升到10的数千)。名单的长度几乎每天都在变化。所以我想把这个列表分成300个小列表,但是我想动态地定义这些小列表的名称。你知道吗

即:

main_list = ['1029', '2314', '466754', '6345', '3456' ....]

list1 = ['1029', '2314' ... first 300 elements]
list2 = ['342343', '3425' ...  next 300 elements]

等等。你知道吗


Tags: 项目名称列表定义main动态数字elements
3条回答

拆分为块,并使用dict按名称/键访问每个块:

d = {}
chnks = (main_list[i:i+300]for i in range(0, len(main_list), 300))

for ind, chnk in enumerate(chnks,1):
    d["list_{}".format(ind)] = chnk

print(d)

以较小的输入大小为例:

main_list = ['1029', '2314', '466754', '6345', '3456',"4456"]
d = {}
chnks = (main_list[i:i+2]for i in range(0, len(main_list), 2))

for ind, chnk in enumerate(chnks,1):
    d["list_{}".format(ind)] = chnk

print(d)
{'list_3': ['3456', '4456'], 'list_2': ['466754', '6345'], 'list_1': ['1029', '2314']}

您可以使用列表列表和按索引访问,但如果您只想将列表拆分为块并在不需要dict或列表列表时使用每个块,只需遍历生成器并传递每个块即可。你知道吗

gbl不过是一个变量和值的字典,您可以使用range拆分列表,并通过定义dictionary中的key来定义一个新变量

gbl=globals()
for j,i in enumerate(range(0,len(main_list),2),1):
    gbl["list"+str(j)]=main_list[i:i+2]

输入

['1029', '2314', '466754', '6345', '3456']

输出

list1=['1029','2134']
list2=['466754','6345']
list3=['3456']

This data goes to an external system which can handle at max 400 requests at one time.

def process_sublist(i, sublist):
    """Deliver this i-th sublist to the external system."""
    pass

def process_list(main_list, sublist_size):
    """Split main_list into sublists and call process_sublist."""
    for i in range(0, len(main_list), sublist_size):
        index = i / sublist_size
        sublist = main_list[i:i+sublist_size]
        process_sublist(index, sublist)

# Use the function process_list.
main_list = ['1029', '2314', '466754', '6345', '3456', ...]
process_list(main_list, 300)

相关问题 更多 >