我有一些np.datetimes列表,我想给它们加上一个浮点数:
list_of_floats=[0.01,0.02,0.01]
list1=[np.datetime64('2016-07-01'),
np.datetime64('2017-03-01')]
list2=[np.datetime64('2016-07-01'),
np.datetime64('2017-03-01')]
list3=[np.datetime64('2016-07-01'),
np.datetime64('2017-03-01')]
list_of_lists=[list1,list2,list3]
这是我尝试过的:
for i in range(len(list_of_floats)):
list_of_lists[i].append(list_of_floats[i])
print(list_of_lists)
所需的输出:
[[np.datetime64('2016-07-01'),np.datetime64('2017-03-01'),0.01],
[np.datetime64('2016-07-01'),np.datetime64('2017-03-01'),0.02]
[np.datetime64('2016-07-01'),np.datetime64('2017-03-01'),0.01]]
我该如何克服这个问题?
答案 0 :(得分:2)
使用enumerate
例如:
import numpy as np
list_of_floats=[0.01,0.02,0.01]
list1=[np.datetime64('2016-07-01'),
np.datetime64('2017-03-01')]
list2=[np.datetime64('2016-07-01'),
np.datetime64('2017-03-01')]
list3=[np.datetime64('2016-07-01'),
np.datetime64('2017-03-01')]
list_of_lists=[list1,list2,list3]
for i, v in enumerate(list_of_floats):
list_of_lists[i].append(v)
print(list_of_lists)
或使用zip
例如:
for i, v in zip(list_of_floats, list_of_lists):
v.append(i)
输出:
[[numpy.datetime64('2016-07-01'), numpy.datetime64('2017-03-01'), 0.01],
[numpy.datetime64('2016-07-01'), numpy.datetime64('2017-03-01'), 0.02],
[numpy.datetime64('2016-07-01'), numpy.datetime64('2017-03-01'), 0.01]]
答案 1 :(得分:1)
您可以利用zip
import numpy as np
list_of_floats=[0.01, 0.02, 0.01]
list_of_lists=[
[np.datetime64('2016-07-01'), np.datetime64('2017-03-01')],
[np.datetime64('2016-07-01'), np.datetime64('2017-03-01')],
[np.datetime64('2016-07-01'), np.datetime64('2017-03-01')],
]
for date_list, float_number in zip(list_of_lists, list_of_floats):
date_list.append(float_number)
print(list_of_lists)