Skip to main content
 首页 » 编程设计

python之高效的列表复制

2024年10月24日7shanyou

我有一些有效的代码,但我担心它的效率真​​的很低。是否有更高效的方法将字典列表分块/批处理到某种缓冲区中。

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 个 block 。在生产中,我希望有 10,000 个 block ,并且 rows[] 将有 1,000,000 个条目

如前所述,这似乎确实有效,但感觉缓慢且效率低下,尤其是附加到列表并重置它。

谁能建议更好的方法。

请您参考如下方法:

将列表 A 拆分为两个:

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']]