将列表有效地合并到稀疏列表中

时间:2018-06-13 07:21:37

标签: python list performance

我有两个清单:

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .custom({ AnyKey(stringValue: $0.last!.stringValue.lowercased())!}) 
decoder.dateDecodingStrategy = .secondsSince1970
let coinList = try decoder.decode(CoinList.self, from: data)
print(coinList)

我想合并它们,要么创建一个新列表,要么只是通过用b中的值填充Nones来更新a,所以

a = [None, None, 1, None, 4, None, None, 5, None]
b = [7,8,2,3,6,9]

最有效的方法是什么?

对于扩展,我想要对b的每个排列都这样做。这是否允许简化技术?

5 个答案:

答案 0 :(得分:6)

这是一种方法。使用列表推导并将b转换为迭代器对象。

<强>演示:

a = [None, None, 1, None, 4, None, None, 5, None]
b = [7,8,2,3,6,9]
b = iter(b)

print( [next(b) if i is None else i for i in a] )

<强>输出:

[7, 8, 1, 2, 4, 3, 6, 5, 9]

答案 1 :(得分:3)

for reversed_index in range(len(a) - 1, -1, -1):
    if a[reversed_index] is None:
        a[reversed_index] = b.pop()

它应该是有效的,因为它修改了a并且正确弹出列表也是有效的。据我所知,这是一个O(len(a))解决方案。

答案 2 :(得分:3)

使用list.pop()方法反转第二个b列表:

a = [None, None, 1, None, 4, None, None, 5, None]
b = [7,8,2,3,6,9]
tmp = b[::-1]

result = [tmp.pop() if i is None else i for i in a]
print(result)    # [7, 8, 1, 2, 4, 3, 6, 5, 9]

答案 3 :(得分:1)

递归apporach:

a = [None, None, 1, None, 4, None, None, 5, None]
b = [7,8,2,3,6,9]

def recursion_approach(first_list,second_list):

    for index,value in enumerate(first_list):
            if value!=None:
                first_list[index]=value
            else:
                first_list[index]=second_list[0]
                recursion_approach(first_list,second_list[1:])

    return first_list

print(recursion_approach(a,b))

输出:

[7, 8, 1, 2, 4, 3, 6, 5, 9]

答案 4 :(得分:1)

对于具有较大列表的性能,您可能会发现第三方库更有效,例如通过Pandas或NumPy。

熊猫

创建2个系列并将其与布尔索引一起使用:

import pandas as pd

a = pd.Series([None, None, 1, None, 4, None, None, 5, None])
b = pd.Series([7,8,2,3,6,9])

a[a.isnull()] = b.values

print(a.values.astype(int).tolist())

# [7, 8, 1, 2, 4, 3, 6, 5, 9]

numpy

与NumPy类似,只要您使用np.nan而不是None

import numpy as np

a = np.array([np.nan, np.nan, 1, np.nan, 4, np.nan, np.nan, 5, np.nan])
b = np.array([7,8,2,3,6,9])

a[np.isnan(a)] = b

# array([ 7.,  8.,  1.,  2.,  4.,  3.,  6.,  5.,  9.])

另请参阅What are the advantages of NumPy over regular Python lists?