Python面向对象模型

发布于 2024-09-10 13:11:36 字数 705 浏览 2 评论 0原文

我有类似以下内容。

拥有属于某个州的多种颜色的同一型号汽车的人。

我设计了一个具有属性 人名汽车型号汽车年份汽车状态汽车颜色作为属性。颜色应该是一个列表,因为一个人可以拥有许多不同颜色但同一型号的汽车。

现在我如何找到并打印两个拥有相同型号汽车和相同颜色汽车但在面向对象方面属于不同州的不同人?

我是Python新手。

在将颜色插入人员对象时,如何插入到列表中以及如何从列表中检索?我知道如何对属性执行此操作,但我对列表操作有点困惑。

数据可以是这样的:

person1 ford   [red,blue,yellow] new-york
person2 honda  [red,blue]        new-york
person3 ford   [red,grey]        california
person4 ford   [red]             california
person5 honda  [red]             new-york

现在我的结果应该只是:

[(person1,person5)]    (same model car,same color, different state)

I have something like the follwing.

A person having many colors of cars of the same model belonging to some state.

I have designed a person class as having attributes person name, car model, car year, car state, and car color as attributes. And color should be a list as a person can have many cars of different colors but of the same model.

Now how do I find and print 2 different people who have same model of car and same color of car but belong to different states in object oriented terms?

I am new to Python.

While inserting color into the person object how do I insert into the list and how do I retrieve from the list? I know how to do it for an attribute, but I am a little confused about list operations.

The data can be like this:

person1 ford   [red,blue,yellow] new-york
person2 honda  [red,blue]        new-york
person3 ford   [red,grey]        california
person4 ford   [red]             california
person5 honda  [red]             new-york

Now my result should only be:

[(person1,person5)]    (same model car,same color, different state)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

旧时浪漫 2024-09-17 13:11:36

你想了解一些关于列表操作的知识:

$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> l=[]
>>> l.append("honda")
>>> l.append("ford")
>>> l
['honda', 'ford']
>>> l[0]
'honda'
>>> l.pop(0)
'honda'
>>> l.pop(0)
'ford'
>>> l.pop(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: pop from empty list

如果你想找到几个具有匹配属性的人,你可以做一些
迭代(这里用一些伪代码表示,因为我认为重点在于
该算法比专注于 python 来实现它更有用):

results = []
foreach p1 in [list of people]
    foreach p2 in [list of people]
        next if p1 == p2
        next if p1.state == p2.state
        next unless p1.car == p2.car
        foreach c1 in p1.colors
            foreach c2 in p2.colors
                results.append((p1,p2)) if c1 == c2

此代码对人进行比较。它不会将一个人与
他们自己。它不会比较生活在同一州的人,因为你
要求“..但属于不同的州”。所以让我们过滤那些相同状态的
人们出去。它只比较拥有相同类型汽车的人。 (如果
人们拥有不同类型的汽车,那么你只需再添加两辆嵌套的汽车
循环。)然后它会注意到拥有相同颜色汽车的两对人。

该算法存在一个潜在的错误:它会报告 [(person1, person2),
(人物2,人物1)]
。因此条目是重复的。可以修改一下
如果您不这样做,则仅搜索人员的上三角或下三角的算法
想要这个重复:

results = []
for i=0; i<people.last_index-1; i++
    for j=i+1; j<people.last_index ; j++
        p1 = people[i] ; p2 = people[j]
        next if p1.state == p2.state
        next unless p1.car == p2.car
        foreach c1 in p1.colors
            foreach c2 in p2.colors
                results.append((p1,p2)) if c1 == c2

请注意,我们可以删除 next if p1 == p2 检查,因为我们明确不能
得到i == jj 定义为以 i+1 开头。

You wanted to know a little about list manipulation:

$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> l=[]
>>> l.append("honda")
>>> l.append("ford")
>>> l
['honda', 'ford']
>>> l[0]
'honda'
>>> l.pop(0)
'honda'
>>> l.pop(0)
'ford'
>>> l.pop(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: pop from empty list

If you want to find several persons with matching attributes, you could do some
iteration (represented here in some psuedo-code, because I think focussing on
the algorithm is more useful than focussing on the python to make it happen):

results = []
foreach p1 in [list of people]
    foreach p2 in [list of people]
        next if p1 == p2
        next if p1.state == p2.state
        next unless p1.car == p2.car
        foreach c1 in p1.colors
            foreach c2 in p2.colors
                results.append((p1,p2)) if c1 == c2

This code compares pairs of people. It doesn't compare a person against
themself. It doesn't compare people who live in the same state because you
asked for ".. but belong to different states". So let's filter those same-state
people out. It compares only people who own the identical kind of car. (If
people owned different types of cars, then you'd just add two more nested for
loops.) Then it notes the pairs of people that have the same color of car.

There's a potential bug in this algorithm: it'll report [(person1, person2),
(person2, person1)]
. So entries are duplicated. It's possible to amend the
algorithm to search just the upper or lower triangle of people if you don't
want this duplication:

results = []
for i=0; i<people.last_index-1; i++
    for j=i+1; j<people.last_index ; j++
        p1 = people[i] ; p2 = people[j]
        next if p1.state == p2.state
        next unless p1.car == p2.car
        foreach c1 in p1.colors
            foreach c2 in p2.colors
                results.append((p1,p2)) if c1 == c2

Note we can remove the next if p1 == p2 check because we explicitly cannot
get i == j. j is defined to start with i+1.

婴鹅 2024-09-17 13:11:36

您可能希望将 statecarperson 分开建模。然后,每个人都可以拥有汽车列表,并居住在一个州(甚至是一个州列表,具体取决于您的型号)。这些是关系。如果您愿意,它还允许您稍后对 car 进行子类化并创建 sportsCar

You might want to model state and car separately from person. Then, each person can have a list of cars, and live in a state (or even a list of states, depending on your model). These are has-a relationships. It will also allow you to subclass car later and make sportsCar later, if you want.

只等公子 2024-09-17 13:11:36

有很多方法可以做到这一点。如果您有大量数据,那么我建议您继续使用 python 的内置 sqlite 支持来处理基于数据库的实现(实际上并不难)。数据库引擎是专门为搜索而构建的。您需要两张桌子,因为每个人可以有多种颜色。 person 表将包含以下列:id、name、model、state。颜色表将包含:personid、颜色。 personid 列将包含颜色表中的行对应的 ID 号。然后,您可以在颜色表中包含具有相同 personid 值(这是列表的数据库版本)的多行。 sqlAlchemy 是一个帮助使用 python 对象实现数据库的库,您可能会发现它更适合您想要做的事情。 sqlAlchemy ORM 教程将引导您使用具有两个表(用户、地址)与您需要的非常相似。

现在,如果您想单独使用 python 类,您将必须有一个人员实例列表,并遍历它们以查找匹配项。颜色匹配的一个方便的简化是将颜色列表转换为集并进行交集。

>>> s1 = set(['red','blue','yellow'])
>>> s2 = set(['red','blue'])
>>> s1.intersection(s2)
set(['blue', 'red'])

通过人员实例列表进行迭代的快捷方式是使用 python 的 itertools 库并使用排列生成器。

from itertools import permutations
people = ['p1', 'p2', 'p3']
for p1, p2 in itertools.permutations(people,2):
    print p1, p2

p1 p2
p1 p3
p2 p1
p2 p3
p3 p1
p3 p2

希望这足以帮助您一路走来。重新阅读你的问题,看起来你可能需要更多地阅读有关 python 编程的内容。但是为了解决您关于列表的问题,这里有一些代码可以帮助您。

class Person(object):
    def __init__(self, name, model, colors, state):
        self.name = name
        self.model = model
        self.colors = colors
        self.state = state

p1 = Person('p1', 'ford', ['red', 'blue'], 'new-york')
p2 = Person('p2', 'honda', ['red', 'blue'], 'new-york')

persons = [p1, p2]
  # or
persons = []
persons.append(p1)
persons.append(p2)

p1.color.append('yellow')
  # or
persons[0].color.append('yellow')

There are a bunch of ways to do this. If you have a lot of data then I'd recommend that you go ahead and tackle a database based implementation using python's built-in sqlite support (which is actually not that hard). A database engine is purpose built for searching. You would need two tables since you can have multiple colors per person. The person table would have the following columns: id, name, model, state. The colors table would have: personid, color. The personid column would contain the id number that the row in the color table corresponds to. You can then have multiple rows in the color table with the same personid value (which is the database version of a list). sqlAlchemy is a library to help implement a database using python objects which you may find more appropriate with what you are trying to do. The sqlAlchemy ORM Tutorial walks you through working with an sqlite database with two tables (users, addresses) that are very similar to what you would need.

Now if you want stick with python classes alone you are going to have to have a list of people instances and iterate through them all looking for matches. A handy simplification for your color matching is to convert the color lists to sets and do an intersection.

>>> s1 = set(['red','blue','yellow'])
>>> s2 = set(['red','blue'])
>>> s1.intersection(s2)
set(['blue', 'red'])

A shortcut for your iteration through the list of people instances is to use python's itertools library and use the permutations generator.

from itertools import permutations
people = ['p1', 'p2', 'p3']
for p1, p2 in itertools.permutations(people,2):
    print p1, p2

p1 p2
p1 p3
p2 p1
p2 p3
p3 p1
p3 p2

Hopefully this is enough to help you along your way. Rereading your question it looks like you may need to do more reading on programming in python. But to address your question about lists here is a little bit of code that may help you out.

class Person(object):
    def __init__(self, name, model, colors, state):
        self.name = name
        self.model = model
        self.colors = colors
        self.state = state

p1 = Person('p1', 'ford', ['red', 'blue'], 'new-york')
p2 = Person('p2', 'honda', ['red', 'blue'], 'new-york')

persons = [p1, p2]
  # or
persons = []
persons.append(p1)
persons.append(p2)

p1.color.append('yellow')
  # or
persons[0].color.append('yellow')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文