简体   繁体   English

保存每个 for 循环迭代的 output 以拆分嵌套列表

[英]save the output of each for loop iteration to split a nested list

I have a list of lists that looks like this mylst我有一个看起来像这样的列表列表mylst

[[('Salmon', 9), ('Fish&Chips', 3), ('Pasta', 8), ('Shrimp', 10)],
 [('Shrimp', 8), ('Fish&Chips', 10), ('Salmon', 9), ('Pasta', 7)],
 [('Shrimp', 10), ('Fish&Chips', 6), ('Salmon', 8), ('Pasta', 5)],
 [('Shrimp', 7), ('Pasta', 9), ('Salmon', 8), ('Fish&Chips', 8)],
 [('Fish&Chips', 10), ('Shrimp', 8), ('Salmon', 9), ('Pasta', 3)]]

I can access the sublists if I print the desired index如果我打印所需的索引,我可以访问子列表

mylst[0]

which returns返回

[('Salmon', 9), ('Fish&Chips', 3), ('Pasta', 8), ('Shrimp', 10)]

But I would like to store each sublist in a new list.但我想将每个子列表存储在一个新列表中。

Because eventually I would like to extract the items(tuple index 0) and the quantity ordered (tuple index 1) for each sublist and store them in two separate lists.因为最终我想为每个子列表提取项目(元组索引 0)和订购数量(元组索引 1)并将它们存储在两个单独的列表中。 But I can't do this if I can't split the lists但如果我不能拆分列表,我就不能这样做

I tried to iterate through the main list我试图遍历主列表

newlst=[]

for sublst in mylst:
    newlst.append(sublst)

and

newlst=[]

for i in range(len(mylst)):
    for sublst in mylst:
        newlst.append(mylst[i])

I am not sure how to split then store multiple outputs from each iteration of the for loop.我不确定如何从 for 循环的每次迭代中拆分然后存储多个输出。

The desired output is to have the 5 sublists as seperate lists.所需的 output 是将 5 个子列表作为单独的列表。 For example例如

lst1=[('Salmon', 9), ('Fish&Chips', 3), ('Pasta', 8), ('Shrimp', 10)]

lst2 = [('Shrimp', 8), ('Fish&Chips', 10), ('Salmon', 9), ('Pasta', 7)]

and so on.等等。

note: my question is not duplicate of this one , as I have read the solutions.注意:我的问题与这个问题不重复,因为我已经阅读了解决方案。 I want to store my sublists in seperate lists.我想将我的子列表存储在单独的列表中。 which is different.这是不同的。

If you just want to unpack the list then you can do what Chris said above and just do a,b,c,d,e = mylst , but if what you want is to repackage the data in a more usable way, then I suggest storing this in a pandas dataframe.如果您只想解压列表,那么您可以按照 Chris 上面所说的做a,b,c,d,e = mylst ,但是如果您想要以更有用的方式重新打包数据,那么我建议将其存储在 pandas dataframe 中。 You can do that with the following code您可以使用以下代码执行此操作

import numpy as np
import pandas as pd

my_df = pd.DataFrame(np.array(mylst).reshape(-1, 2),
    columns=['item', 'quantity']) 

You can make one massive nested list by using a for loop each containing the desired list.您可以使用一个包含所需列表的for循环来制作一个庞大的嵌套列表。

for each in lst:
seplist = [] #splitted list of each digit of every integer
for eachagain in str(each):
    seplist.append(integer)
nestedlist.append(seplist)

Here the nested list can be separated and stored by using another for loop这里可以使用另一个for循环来分离和存储嵌套列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM