高效的列表复制

时间:2016-05-27 04:21:43

标签: python python-3.x

我有一些有用的代码,但我担心它的效率非常低。是否有一种更高效的方法可以将一个字典列表分块/批处理成一种缓冲区。

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个块中的数字列表。在生产中我希望有10,000个块,行[]将有1,000,000个条目

如上所述,这似乎有效,但感觉速度慢且效率低,尤其是附加到列表并重置它。

任何人都可以建议更好的方法。

1 个答案:

答案 0 :(得分:2)

将列表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']]
相关问题