简体   繁体   English

python中包含多个变量的项目列表

[英]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. 我读了dict,但这里只有两个变量。 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]) 现在,尽管这行得通,但您必须尝试记住所有内容的数值(您当然可以将'age = 1'并将其细分为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) 在这里,我们能够存储一个类的“实例”,这些实例都包含自己的变量,可以轻松更改和重新打印这些变量(list [0] .x = 15)

Let me know if you need anymore help or want a more specific example. 让我知道您是否需要更多帮助或需要更具体的示例。

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

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