這是我第一次用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