简体   繁体   English

如何在Python中存储类似C的结构的列表?

[英]How can I store a list of C-like structures in Python?

Let me explain the problem by a simple example: 让我通过一个简单的例子来说明问题:

Let's say I want to store 100 people's name, and brand(s) of the car(s) they own (so there can be 1 or more). 假设我要存储100个人的姓名和他们所拥有汽车的品牌(因此可以存储1个或更多)。

I was thinking about using dictionary in Python, but is can only store 1 string attached to one name. 我当时正在考虑在Python中使用字典,但只能存储1个附加到一个名称的字符串。 Perhaps I can seperate the cars' names like this: 也许我可以这样分隔汽车的名称:

people_and_cars = {'Jack':'Opel Audi'}

and when I need them, I can seperate it into 'Opel' and 'Audi by the split() function, but it seems a bit silly solution. 当我需要它们时,可以通过split()函数将其分为“ Opel”和“ Audi”,但这似乎有点愚蠢的解决方案。

Is there a better way to do this? 有一个更好的方法吗?

You can store your data in a dictionary: 您可以将数据存储在字典中:

people_and_cars = {}

Jack has an Opel car, but he might buy another one later, so I store this one in a list like this: 杰克有一辆欧宝汽车,但他可能以后会再买一辆,所以我将其存储在这样的列表中:

people_and_cars['Jack'] = ['Opel']

print(people_and_cars)  # Output: {'Jack': ['Opel']}

Now, Jack buys a new Audi car, so I add it as follows: 现在,杰克购买了一辆新的奥迪汽车,因此我将其添加如下:

people_and_cars['Jack'].append('Audi')

print(people_and_cars)  # Output: {'Jack': ['Opel', 'Audi']}

You may need to check first whether a person exists in your dictionary or not, you can do that like below: 您可能需要首先检查词典中是否存在某个人,您可以按照以下步骤进行操作:

if person in people_and_cars:
    people_and_cars[person].append(car)
else:
    people_and_cars[person] = [car]

Store the list of the cars for each person as a list. 将每个人的汽车列表存储为列表。 The list will be then the values of the keys (people) in your dictionary. 列表将是字典中键(人物)的值。

For your example: 例如:

people_and_cars = dict()
people_and_cars['Jack'] = ["Opel", "Audi"]

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

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