这是我第一次用Python做这么大的工作,所以我需要一些帮助。使用大数据集优化循环Python
我有一个MongoDB的(或Python字典)结构如下:
{
"_id": { "$oid" : "521b1fabc36b440cbe3a6009" },
"country": "Brazil",
"id": "96371952",
"latitude": -23.815124482000001649,
"longitude": -45.532670811999999216,
"name": "coffee",
"users": [
{
"id": 277659258,
"photos": [
{
"created_time": 1376857433,
"photo_id": "525440696606428630_277659258",
},
{
"created_time": 1377483144,
"photo_id": "530689541585769912_10733844",
}
],
"username": "foo"
},
{
"id": 232745390,
"photos": [
{
"created_time": 1369422344,
"photo_id": "463070647967686017_232745390",
}
],
"username": "bar"
}
]
}
现在,我要创建两个文件,一个与摘要和其他与每个连接的权重。我的环路,适用于小型数据集如下:
#a is the dataset
data = db.collection.find()
a =[i for i in data]
#here go the connections between the locations
edges = csv.writer(open("edges.csv", "wb"))
#and here the location data
nodes = csv.writer(open("nodes.csv", "wb"))
for i in a:
#find the users that match
for q in a:
if i['_id'] <> q['_id'] and q.get('users') :
weight = 0
for user_i in i['users']:
for user_q in q['users']:
if user_i['id'] == user_q['id']:
weight +=1
if weight>0:
edges.writerow([ i['id'], q['id'], weight])
#find the number of photos
photos_number =0
for p in i['users']:
photos_number += len(p['photos'])
nodes.writerow([ i['id'],
i['name'],
i['latitude'],
i['longitude'],
len(i['users']),
photos_number
])
的结垢问题:我有20000点的位置,每个位置最多可以有2000个用户,每个用户可能有大约10张照片。
有没有更有效的方法来创建上述循环?也许多线程,JIT,更多的索引? 因为如果我在单线程中运行以上可以达到20000^2 * 2000 * 10的结果...
那么我怎样才能更有效地处理上述问题呢? 感谢
样式更改:用'!='替换'<>'。另外,“a”中有什么? – Tadeck
'a'代表字典。我更新了我的问题。 – Diolor
我不认为它代表字典。否则'因为我在a'会迭代_keys_,所以进一步使用'i''_ id']'键会产生一个错误。我想这是一个列表。 – Tadeck