简体   繁体   中英

list of items containing more than one variable in python

I want to create a list of items where each item may have more than one variable. I read about dict, but there its just two variables. Then I thought of class. However I am not sure how to implement class object inside a list. I would also like to store the data in a db. Can you give me an explanation of how to implement this logic in the code?

There are a few ways you can do this. I'll go from easy to harder.

  1. Multi-dimensional arrays

A multi-dimensional array is like an array inside an array, like this:

If we wanted to store pets with their animal type and age

    CODE:
    multi-array = [["dog", 8], ["cat", 10]]
    DanielsPet = multi-array[0]
    print(DanielsPet[1])

    RESULT:
    8

Now although this works you have to try and remember a numerical value for everything (you could of course have 'age = 1' and sub that into DanielsPet[age])

  1. Multiple instances of classes

Now it sounds like you haven't looked into classes very much so I am going to be brief with this one, let me know if you want more information.

Steps:

  1. create the class
  2. put instances of that class in a list
  3. read / edit the instances

     #basic class class basic: def __init__(self, x, y): self.x = x self.y = y list = [basic(5, 10), basic(10, 20)] print (list[0].x, list[1].y) list[0].x = 15 print (list[0].x, list[1].y) RESULT: (5, 20) (15, 20) 

Here we are able to store 'instances' of a class which all contain their own variables, these can easily be changed and reprinted (list[0].x = 15)

Let me know if you need anymore help or want a more specific example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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