2016-05-27 68 views
2

我有一些可行的代碼,但我擔心它真的效率低下。是否有一種更高效的方式將dict的列表分塊/分配到一種緩衝區中。高效的列表複製

rowA = {1:"a",2:"b",3:"c"}   # Random dict 
rowB = {4:"d",5:"e",6:"f"}   # Random dict 
rowC = {7:"g",8:"h",9:"i"}   # Random dict 
rowD = {0:"j",1:"k",2:"l"}   # Random dict 
rows = [rowA ,rowB ,rowC ,rowD ] # Add to a List 
row_chunk = []      # Empty List for buffer/cache 
row_count = 0      # Counter for buffer size 
for row in rows:       # Iterate over the list 
    row_chunk.append(list(row.values())) # Append the values from the dictionary 
    row_count += 1      # Increment the buffer size 
    if row_count % 2 == 0:    # Check if the buffer reached level 
     print("We have {0} dictionaries".format(len(row_chunk))) 
     row_chunk = []     # Reset the list 

在這個例子中,我打破號碼列表中的2塊在生產中我希望有10000塊,行[]將有1,000,000條記錄

如前所述但這似乎工作,但感覺速度慢,效率低,尤其是追加到列表並重新設置。

任何人都可以建議一個更好的方法。

+1

爲什麼你使用這個緩衝區? – BrenBarn

+0

使用'list(row.values())'的任何特定原因? – Copperfield

+0

@BrenBarn - 沒有特別的原因。這基本上是緩衝寫入數據庫。只要我不試圖一次提交整行[],我就不在乎如何分解它。 – Exie

回答

2

要分割列表的分爲兩個:

Part1=A[:len(A)/2] 
Part2=A[len(A)/2:] 

我想這是所有你需要:

>>> for row in rows:       # Iterate over the list 
...  A.append(list(row.values())) 
... 
>>> A=row_chunk 
>>> B=A[:len(A)/2] 
>>> C=A[len(A)/2:] 
>>> A 
[['a', 'b', 'c'], ['d', 'e', 'f'], ['h', 'i', 'g'], ['j', 'k', 'l']] 
>>> B 
[['a', 'b', 'c'], ['d', 'e', 'f']] 
>>> C 
[['h', 'i', 'g'], ['j', 'k', 'l']] 

備選:(直接獲取值,避免環路)

>>> rows = [rowA.values() ,rowB.values() ,rowC.values() ,rowD.values() ] # Add to a List 
>>> rows 
[['a', 'b', 'c'], ['d', 'e', 'f'], ['h', 'i', 'g'], ['j', 'k', 'l']] 
>>> A=rows[:len(rows)/2] 
>>> B=rows[len(rows)/2:] 
>>> A 
[['a', 'b', 'c'], ['d', 'e', 'f']] 
>>> B 
[['h', 'i', 'g'], ['j', 'k', 'l']]