[英]How to directly access class instances through class dictionary in Python
我需要一種通過ID號直接訪問類實例的方法。
正如我在這里嘗試解釋的那樣,我正在導入.csv文件,我想為.csv文件中的每一行創建我的類Person()的實例,而且我希望能夠直接訪問這些實例作為鍵入一個已存在於.csv文件中的唯一標識符。
到目前為止,由於user433831的幫助,我所做的是:
from sys import argv
from csv import DictReader
from person import Person
def generateAgents(filename):
reader = DictReader(open(filename, 'rU'))
persons = [Person(**entry) for entry in reader]
return persons
person只是我將類Person()定義為的模塊:
class Person:
def __init__(self, **kwds):
self.__dict__.update(kwds)
現在我有一個人員實例列表,即persons
,這已經很整潔了。 但是現在我需要使用networkx
模塊在這些人之間創建一個網絡,我肯定需要一種直接訪問每個人的方法(目前我的實例沒有任何名稱)。
例如,每個人都有一個名為“father_id”的屬性,它是父親的唯一ID。 在當前人口中沒有父親的人的“father_id”等於“-1”。
現在,為了將每個人與他/她的父親聯系起來,我會做以下事情:
import networkx as nx
G=nx.Graph()
for person in persons:
G.add_edge(person, person_with_id_equal_to_father_id)
我的問題是我無法直接訪問此“person_with_id_equal_to_father_id”。 請記住,我需要多次直接訪問,所以我需要一種非常有效的方法,而不是在列表中進行某種形式的搜索(也考慮到我的人口中有大約150000人) 。
在我的類Person()中實現類似字典功能的東西會很棒,每個實例的鍵都是唯一的標識符。 這個唯一標識符已存在於我的csv文件中,因此我已將其作為每個人的屬性。
感謝您的幫助,我們非常感謝。 另外請記住我是一個蟒蛇新手(你可能會告訴...;))
只需使用字典:
persons_by_id = {p.id: p for p in persons}
這需要最新版本的Python。 如果您的語法不支持此語法,請使用以下命令:
persons_by_id = dict((p.id, p) for p in persons)
完成上述任一操作后,您可以通過ID找到此人,如下所示:
persons_by_id[id]
networkx
示例變為:
import networkx as nx
G=nx.Graph()
for person in persons:
if person.father_id != -1:
G.add_edge(person, persons_by_id[person.father_id])
這是@Toote建議的有效方式:
def generateAgents(filename):
with open(filename, 'rU') as input:
reader = DictReader(input)
persons = dict((entry['father_id'], Person(**entry)) for entry in reader)
return persons
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.