我需要在Python中用以下列表的值替换空值。 如果列表中的所有项目都不为空,则其值将相同。
列表示例
[[1538140080000, None], [1538140140000, None], [1538140200000, None], [1538140260000, None], [1538140320000, None], [1538140380000, 92881926.0], [1538140440000, 92881926.0]]
我希望得到的输出是
[[1538140080000, 92881926.0], [1538140140000, 92881926.0], [1538140200000, 92881926.0], [1538140260000, 92881926.0], [1538140320000, 92881926.0], [1538140380000, 92881926.0], [1538140440000, 92881926.0]]
在列表中,(键,值)中的任何一个都将具有所需的值(除null之外),我希望将其替换为列表中的所有键。
答案 0 :(得分:0)
let predicate = NSPredicate(format: " %K != %@ AND %K != nil", remoteAttributes.lineOwner, "")
输出
l = [[1538140080000, None], [1538140140000, None], [1538140200000, None], [1538140260000, None], [1538140320000, None], [1538140380000, 92881926.0], [1538140440000, 92881926.0]]
replacement = next(filter(None, list(zip(*l))[1]))
for sl in l:
for i, x in enumerate(sl):
if x is None:
sl[i] = replacement
print(l)
答案 1 :(得分:0)
列表理解可以轻松完成任务
l = [[q if q else 0 for q in i] for i in l]
输出
[[1538140080000, 0], [1538140140000, 0], [1538140200000, 0], [1538140260000, 0], [1538140320000, 0], [1538140380000, 92881926.0], [1538140440000, 92881926.0]]
已更新
var = [[i[q] for i in l if i[q]] for q in range(len(l[0]))]
l = [[q if q else var[w][0] for w,q in enumerate(i)] for i in l]
输出
[[1538140080000, 92881926.0], [1538140140000, 92881926.0], [1538140200000, 92881926.0], [1538140260000, 92881926.0], [1538140320000, 92881926.0], [1538140380000, 92881926.0], [1538140440000, 92881926.0]]
答案 2 :(得分:0)
如果您进行硬编码替换,则可能是单行。
此外,如果您允许懒惰求值,则可以消除list(...)调用。
replacement = 0
l = list( map(lambda (a,b): [a,replacement if b == None else b], l) )
答案 3 :(得分:0)
如果您愿意使用第三方库,Pandas提供了矢量化方法:
import pandas as pd
L = [[1538140080000, None], [1538140140000, None], [1538140200000, None],
[1538140260000, None], [1538140320000, None], [1538140380000, 92881926.0],
[1538140440000, 92881926.0]]
res = pd.DataFrame(L).bfill().ffill().values.tolist()
print(res)
[[1538140080000.0, 92881926.0], [1538140140000.0, 92881926.0], [1538140200000.0, 92881926.0],
[1538140260000.0, 92881926.0], [1538140320000.0, 92881926.0], [1538140380000.0, 92881926.0],
[1538140440000.0, 92881926.0]]
答案 4 :(得分:0)
获取不是None
的值,因为它将永远只是一个值,我们可以使用set
将l
中的项目重新定义为[i[0], *value]
value = set([y for x, y in l if y != None])
l = [[i[0], *value] for i in l]
[[1538140080000, 92881926.0], [1538140140000, 92881926.0], [1538140200000, 92881926.0], [1538140260000, 92881926.0], [1538140320000, 92881926.0], [1538140380000, 92881926.0], [1538140440000, 92881926.0]]