-1

I've got a class Animal, with attributes Name, Age, Gender and Species. I've got a list with split elements like this:

li = ['George', '23', 'Monkey', 'Male', 'Mike', '31', 'Racoon', 'Male']

Now I want to take four elements at a time, and add to new Animal objects. I really can't figure out how to. Can someone help me with this?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
B.Doe
  • 1
  • Welcome to Stack Overflow! Please review our [SO Question Checklist](http://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist) to help you to ask a good question, and thus get a good answer. – Joe C Nov 17 '16 at 22:28
  • Which part precisely are you stuck on? Iterating over the list in chunks of four items? Creating the instance from those four items? – jonrsharpe Nov 17 '16 at 22:33
  • Possible duplicate of [What is the most "pythonic" way to iterate over a list in chunks?](http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks) – Tadhg McDonald-Jensen Nov 17 '16 at 22:35
  • @jonrsharpe well for starters the "chunking" of the list. I've read the other posts as well, but I can't make them work. The next step is also to put these new class objects into a new list. – B.Doe Nov 17 '16 at 22:56
  • 2
    Then ask **one specific question**. You say you've read other posts but *"can't make them work"* - which posts? What did you try? What precisely went wrong? *Then* you have a decent question. At the moment it reads a lot like you want tutoring, which SO is not for, please [edit] to give a [mcve] per [ask]. – jonrsharpe Nov 17 '16 at 22:58

1 Answers1

0

This may help you get started:

class Animal(object):
    def __init__(self, Name, Age, Species, Gender):
        self.name = Name
        self.age = Age
        self.species = Species
        self.gender = Gender

li = ['George', '23', 'Monkey', 'Male', 'Mike', '31', 'Racoon', 'Male']

first_animal = Animal(*li[0:4])
second_animal = Animal(*li[4:])

print("""
First Animal is:
gender: {0.gender}
age: {0.age}
name: {0.name}
species: {0.species}""".format(first_animal))

Outputs:

First Animal is:
gender: Male
age: 23
name: George
species: Monkey

A brief explanation, "chunking of the list" can be done many ways, I just chose to use the *, splat operator, and slice the contents.

Instantiating objects from the class was borrowed from this tutorial Learn Python the Hard Way, bottom of the page "A First Class Example".

I didn't put these new class objects into a new list, but as everything in python is an object, and you know how to create lists as you did in your question, I'll leave that trivial part out.

Hope this helps.

Tadhg McDonald-Jensen
  • 20,699
  • 5
  • 35
  • 59