![](/img/trans.png)
[英]Extract words from list of lists and store them in a separate variable in python
[英]how to store values from a list of lists into a separate list in python?
我有一个列表列表,并希望将它的一些值存储在一个单独的列表中。 我的列表列表称为data
,它是从数据文件中解析的。 数据文件的标题标记了它下面的值所代表的内容。
标题看起来像这样: fruit, animal, technology, drink, color
data
的前几个元素看起来像这样:
[[apple, dog, phone, water, black],
[banana, cat, laptop, milk, pink],
[melon, bird, computer, juice, green]]
我想按类别对值进行分组,以便对其进行排序。 这是一个相当大的列表,所以我想用一个循环或其他东西来遍历它,但我不知道该怎么做。
我想要一个类似于此的 output 但对于外部列表中的所有元素:
fruits = [apple, banana, melon]
我该怎么做?
感谢任何帮助,因为我是 python 的新手,谢谢!
你真正想做的是旋转一个二维列表。 关于如何做到这一点, 这里有一个很好的答案,但我将总结其背后的主要思想。
如果 x 是您提供的数组,即
x = [[apple, dog, phone, water, black],
[banana, cat, laptop, milk, pink],
[melon, bird, computer, juice, green]]
那么你所需要的就是
rotated = list(zip(*x))
fruits = rotated[0]
animals = rotated[1]
# etc.
它的作用如下:
zip([apple, dog, ...], [banana, cat, ...], [melon, bird, ...])
这假设fruit
总是在索引 0, animal
总是在索引 1,等等。
如果不是这种情况,那么您必须为每个类别构建一组值,然后手动遍历列表以对其进行排序。
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.
您可以将 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:
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']
如果您只想要水果或任何其他列组合,则可以忽略其他部分:
fruits,*_ = map(list,zip(*data))
_,animals,_,drinks,_ = map(list,zip(*data))
或者您可以将数据转换为字典:
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] ]
注意所有 list_of_list[i][0] 是水果,list_of_list[i][1] 是动物等等
因此,您要遍历列表并将列表中的每个项目分配给它们对应的 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.