想知道是否有人可以帮助我解决一些我遇到的小问题。
list1 = [1,2,4]
dz = 0.5
k = max(list1)/dz
print('k =',k)
list1_diff = np.insert(np.diff(list1),0,1)
for item in list1_diff:
#Number of times to repeat number
repeats = item/dz
vec = [np.random.normal(0,1)]*int(repeats)
print(vec)
这产生
[-0.7014481088047718, -0.7014481088047718]
[3.1264015795601274, 3.1264015795601274]
[0.44017976879654314, 0.44017976879654314, 0.44017976879654314, 0.44017976879654314]
这在做些正确的事情,但是我希望循环的输出是将这三个列表作为一个列表。所以应该是
[-0.7014481088047718, -0.7014481088047718, 3.1264015795601274, 3.1264015795601274, 0.44017976879654314, 0.44017976879654314, 0.44017976879654314, 0.44017976879654314]
答案 0 :(得分:1)
你不傻。如果我答对了,那么您希望根据您的公式创建一个包含重复随机数的列表。 您只需要修改一下代码,就像这样:
list1 = [1,2,4]
dz = 0.5
k = max(list1)/dz
print('k =',k)
list1_diff = np.insert(np.diff(list1),0,1)
# create your empty result list, where you add the random numbers in the loop
vec= list()
for item in list1_diff:
# Number of times to repeat number
repeats = item/dz
# add the new random number with it's repeats to the vec list
# using extend
vec.extend([np.random.normal(0,1)]*int(repeats))
# print the result outside the loop, after it has been constructed
print(vec)
答案 1 :(得分:1)
尝试这个:
import numpy as np
list1 = [1,2,4]
dz = 0.5
k = max(list1)/dz
print('k =',k)
list1_diff = np.insert(np.diff(list1),0,1)
final_list=[]
for item in list1_diff:
#Number of times to repeat number
repeats = item/dz
vec = [np.random.normal(0,1)]*int(repeats)
final_list += vec
print(final_list)
答案 2 :(得分:0)
这应该可以完成工作:
import numpy as np
list1 = [1,2,4]
dz = 0.5
k = max(list1)/dz
print(f'k = {k}')
lst = [[np.random.normal(0,1)]*int(item/dz) for item in np.insert(np.diff(list1),0,1)]
flatten = lambda l: [item for sublist in l for item in sublist]
print(flatten(lst))
输出:
k = 8.0
[-1.1762058341816053, -1.1762058341816053, -1.0599923573472354, -1.0599923573472354, 0.6374252888036466, 0.6374252888036466, 0.6374252888036466, 0.6374252888036466]
这里发生了什么
请注意,您也可以使用
extend()
,我打算将其添加到其中,但另一个答案击败了我
答案 3 :(得分:0)
Python列表对此具有内置函数:
String date = "2020-09-28T11:47:37.217";
int from = date.indexOf("T")+1;
int to = from+5;
String timeOfInterest = date.substring(from, to);
System.out.println( timeOfInterest );
例如,
list_name.extend([])
[1、2、3、4、5、6]
因此python extend 函数将列表扩展为另一个列表。它不会附加它!