1

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. the data file had headings which labelled what the values underneath it represented.

the headings looked something like this: fruit, animal, technology, drink, color

the first few elements of data looks something like this:

[[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:

fruits = [apple, banana, melon]

how would i do this?

any help is appreciated as i am new to python, thanks!

miks
  • 25
  • 1
  • 6
  • 1
    How are you categorizing things? And are those supposed to be string literals in the lists, or references to objects? – Carcigenicate Apr 15 '20 at 13:56
  • When would you want a computer to consider `apple` as fruit, `dog` as animal? – Ch3steR Apr 15 '20 at 13:57
  • my actual list of lists is full of numbers but i thought doing that example would make it seem clearer how i wanted it categorized. I'll edit to make it clearer! – miks Apr 15 '20 at 14:03

3 Answers3

3

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, i.e.

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
    zip([apple, dog, ...], [banana, cat, ...], [melon, bird, ...])
  • zip then pulls apart the inner lists, and constructs a zip object.
  • list converts it back to a list.

This assumes that fruit will always be at index 0, animal will always be at index 1, etc.

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.
Guptacos
  • 66
  • 2
3

You can use zip with parameter unpacking to separate the lists directly into variables:

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']

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']
}
Alain T.
  • 40,517
  • 4
  • 31
  • 51
  • oh man i wish i had seen this last bit of code, fruits,animals,techs,drinks,colours = map(list,zip(*x)), earlier! would've saved me from manually doing the names. thanks you! – miks Apr 15 '20 at 14:33
0
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

So you want to loop through the list and assign each item in the list to their corresponding output list

# 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


BobbyBob
  • 3
  • 1
  • 5