简体   繁体   English

如何将列表列表中的值存储到 python 中的单独列表中?

[英]how to store values from a list of lists into a separate list in python?

i have a list of lists and want to store some of its values in a separate list.我有一个列表列表,并希望将它的一些值存储在一个单独的列表中。 my list of lists is called data which was parsed from a data file.我的列表列表称为data ,它是从数据文件中解析的。 the data file had headings which labelled what the values underneath it represented.数据文件的标题标记了它下面的值所代表的内容。

the headings looked something like this: fruit, animal, technology, drink, color标题看起来像这样: fruit, animal, technology, drink, color

the first few elements of data looks something like this: data的前几个元素看起来像这样:

[[apple,  dog,  phone,    water, black], 
     [banana, cat,  laptop,   milk,  pink], 
     [melon,  bird, computer, juice, green]]

i want to group the values by category so that i can sort it.我想按类别对值进行分组,以便对其进行排序。 this quite a large list so i would like to iterate through it all with a loop or something but I'm not sure how to.这是一个相当大的列表,所以我想用一个循环或其他东西来遍历它,但我不知道该怎么做。

i want an output similar to this but for all elements within the outer list:我想要一个类似于此的 output 但对于外部列表中的所有元素:

fruits = [apple, banana, melon]

how would i do this?我该怎么做?

any help is appreciated as i am new to python, thanks!感谢任何帮助,因为我是 python 的新手,谢谢!

What you're really looking to do is rotate a 2d list.你真正想做的是旋转一个二维列表。 There is a great answer here about how to do that, but I'll summarize the main idea behind it.关于如何做到这一点, 这里有一个很好的答案,但我将总结其背后的主要思想。

If x is the array you provided, ie如果 x 是您提供的数组,即

x = [[apple,  dog,  phone,    water, black], 
     [banana, cat,  laptop,   milk,  pink], 
     [melon,  bird, computer, juice, green]]

Then all you need is那么你所需要的就是

rotated = list(zip(*x))
fruits = rotated[0]
animals = rotated[1]
# etc.

What this does is as follows:它的作用如下:

  • *x unpacks x, so that zip is called with *x 解包 x,以便调用 zip
    zip([apple, dog, ...], [banana, cat, ...], [melon, bird, ...])
  • zip then pulls apart the inner lists, and constructs a zip object. zip 然后拉开内部列表,并构造一个 zip object。
  • list converts it back to a list. list 将其转换回列表。

This assumes that fruit will always be at index 0, animal will always be at index 1, etc.这假设fruit总是在索引 0, animal总是在索引 1,等等。

If that's not the case, then you would have to build a set of values for each category, and then iterate through the list manually to sort it out.如果不是这种情况,那么您必须为每个类别构建一组值,然后手动遍历列表以对其进行排序。

knownFruits = {banana, melon, apple, pineapple, guava}
knownAnimals = {dog, cat, bird, leopard, shark}
fruits = []
animals = []

for row in x:
    for elem in row:
        if elem in fruits:
            fruits.append(elem)
        elif elem in animals:
            animals.append(elem)
#etc.

You can use zip with parameter unpacking to separate the lists directly into variables:您可以将 zip 与参数解包一起使用,将列表直接分成变量:

data = [["apple",  "dog",  "phone",    "water", "black"], 
        ["banana", "cat",  "laptop",   "milk",  "pink"], 
        ["melon",  "bird", "computer", "juice", "green"]]

fruits,animals,techs,drinks,colours = map(list,zip(*data))

output: output:

print(fruits)  # ['apple', 'banana', 'melon']
print(animals) # ['dog', 'cat', 'bird']
print(techs)   # ['phone', 'laptop', 'computer']
print(drinks)  # ['water', 'milk', 'juice']
print(colours) # ['black', 'pink', 'green']

if you only want the fruits or any other combinations of columns, you can just ignore the other parts:如果您只想要水果或任何其他列组合,则可以忽略其他部分:

fruits,*_ = map(list,zip(*data))

_,animals,_,drinks,_ = map(list,zip(*data))

Or you could turn your data into a dictionary:或者您可以将数据转换为字典:

keys     = ("fruits","animals","techs","drinks","colours")
dataDict = { key:list(values) for key,values in zip(keys,zip(*data)) }

print(dataDict)

{
 'fruits':  ['apple', 'banana', 'melon'], 
 'animals': ['dog', 'cat', 'bird'], 
 'techs':   ['phone', 'laptop', 'computer'], 
 'drinks':  ['water', 'milk', 'juice'], 
 'colours': ['black', 'pink', 'green']
}
list_of_list = [ [apple, dog, phone, , water, black], 
                 [banana, cat, laptop, milk, pink], 
                 [melon, bird, computer, juice, green] ] 

Notice how all list_of_list[i][0] are fruits, list_of_list[i][1] are animals, etc注意所有 list_of_list[i][0] 是水果,list_of_list[i][1] 是动物等等

So you want to loop through the list and assign each item in the list to their corresponding output list因此,您要遍历列表并将列表中的每个项目分配给它们对应的 output 列表

# initialize the output lists
fruits,animals,devices,drinks,colors = []
for inner_list in list_of_lists:
    fruits.append(inner_list[0])
    animals.append(inner_list[1])
    # repeat for rest of list


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

相关问题 从列表列表中提取单词并将它们存储在python中的单独变量中 - Extract words from list of lists and store them in a separate variable in python 如何从 Python 中的字符串列表中提取完全匹配到单独的列表中 - How to extract exact match from list of strings in Python into separate lists 如何将列表打印到单独的列表中 python - How print a list into separate lists python 如何从一个列表中返回2个单独的列表? - How to return 2 separate lists from a single list? 从列表中提取特定的数据条目(作为组)并存储在单独的列表中? - Extract specific data entries(as groups) from a list and store in separate lists? 如何将python列表上的每月和每天的文件名分成两个单独的列表? - How to separate monthly and daily filenames on python list into two separate lists? 如何将字符列表分成2个单独的列表但在python中保持它们的顺序 - How to separate a list of characters into 2 separate lists but maintain their order in python Python-如何在一个列表中存储多个列表? - Python - how to store multiple lists in one list? 检查3个单独的用户输入是否都与Python中列表列表的值匹配 - Checking if 3 separate User inputs all match the values of a list of lists in Python 如何从列表列表过滤特定的POS标签到单独的列表? - How to filter specific POS tags from list of lists to separate lists?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM