在另一个列表的第 n 个索引处添加列表中的元素

Add elements in a list at the n index of a other list

calibres_prix =['115-135', '1.87'], ['136-165', '1.97'], ['150-180', '1.97'], 
    ['190-220', '1.97'], ['80-95', '1.42'], ['95-115', '1.52'], ['150-180', '1.82'], 
    ['115-135', '1.72'], ['136-165', '1.82'], ['150-180', '1.82'], ['190-220', '1.82'], 
    ['80-95', '1.42'], ['95-115', '1.72'], ['115-135', '1.92'],  ['136-165', '2.02'], 
    ['150-180', '2.02'], ['190-220', '2.02'], ['80-95', '1.27'], ['95-115', '1.57'],
    ['115-135', '1.77'], ['136-165', '1.87'],  ['150-180', '1.87'], ['190-220', '1.87'], 
    ['80-95', '1.37'], ['95-115', '1.67'], ['115-135', '1.87'], ['136-165', '1.97'],
    ['190-220', '1.82'], ['150-180', '1.97'], ['190-220', '1.97'], ['80-95', '1.22'], 
    ['95-115', '1.45'], ['115-135', '1.65'], ['136-165', '1.82'], ['95-115', '1.52']......


varieties=["GOLDEN","GALA","OPAL","GRANNY","CANADE GRISE", "PINK ROSE",
           "CHANTECLER","RED","GOLDRESH","BRAEBURN","STORY"]

大家好, 我想在列表 calibres_prix 中插入品种名称。 calibres_prix [0:23] 品种[0],calibres_prix [24:47] 品种[1],等等....我有 264 个列表 calibres_prix

我想要这个输出:

['GOLDEN','115-135', '1.87']
....
['GALA','190-220', '1.97']

我试试这个:

for i in range(0,len(calibres_prix),24):
    j=i+24
    for l in range(0,len(varieties),1):
        for c in calibres_prix[i:j]:
            c.insert(0,varieties[l])

首先,您应该从 calibres_prix 中创建一个列表,其中仅包含将与 varieties 对象绑定的对象。 然后,您可以使用 zip() 函数来完成这项工作。

table = zip(varieties, calibres_prix)
for variety, prix in table:
    i = [variety, prix[0], prix[1]]
    print(i)

这将是您的输出:

GOLDEN : ['115-135', '1.87']
GALA : ['136-165', '1.97']
OPAL : ['150-180', '1.97']
GRANNY : ['190-220', '1.97']
CANADE GRISE : ['80-95', '1.42']
PINK ROSE : ['95-115', '1.52']
CHANTECLER : ['150-180', '1.82']
RED : ['115-135', '1.72']
GOLDRESH : ['136-165', '1.82']
BRAEBURN : ['150-180', '1.82']
STORY : ['190-220', '1.82']

更多信息,你可以查看这个documenation

关闭!但是,您将所有品种附加到循环中的每个列表。

您可以试试这个:

for i in range(0, len(calibres_prix)):
    calibres_prix[i] = [varieties[i//24]] + calibres_prix[i]

对于 calibres_prix 中的每个列表(我假设这是一个列表列表,因为您没有包含初始 [),添加第 i//24 个品种值开始。

您可以利用 zip(),但是您需要将 varieties 的所有元素重复 24 次:

varieties_repeat_24 = sum(([v]*24 for v in varieties), [])

desired_output = [(variety, *nums) for nums, variety in zip(calibres_prix, varieties_repeat_24)]

请注意,这在内存方面有点浪费。有更好的解决方案...您是否考虑过使用 Pandas?