我有一个代码列表,用于更新每5个元素的时间值。这是代码:
msg = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
theta=1
time=4.5
def get_new_theta(msg, theta,time):
new_theta = [theta]
new_time = [time]
for a, b in zip(msg[3::5], msg[4::5]):
new_theta.append(new_theta[-1] + a + b)
new_time.append(new_time[-1]+time)
return new_theta
return new_time
for i, theta in enumerate(get_new_theta(msg, theta,time)[:-1]):
for j in range(5):
print(theta, msg[i*5+j],time)
但是,我没有得到想要的输出。所需的输出应为:
1 1 4.5
1 2 4.5
1 3 4.5
1 4 4.5
1 5 4.5
10 6 9
10 7 9
10 8 9
10 9 9
10 10 9
29 11 13.5
29 12 13.5
29 13 13.5
29 14 13.5
29 15 13.5
需要此论坛的帮助。谢谢。
答案 0 :(得分:1)
def get_new_theta(msg, theta, time):
new_theta = [theta]
new_time = [time]
for a, b in zip(msg[3::5], msg[4::5]):
new_theta.append(new_theta[-1] + a + b)
new_time.append(new_time[-1]+time)
return new_theta[:-1], new_time[:-1]
msg = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
theta = 1
time = 4.5
for i, (theta, time) in enumerate( zip(*get_new_theta(msg, theta, time)) ):
for j in range(5):
print(theta, msg[i*5+j], time)
给予:
1 1 4.5
1 2 4.5
1 3 4.5
1 4 4.5
1 5 4.5
10 6 9.0
10 7 9.0
10 8 9.0
10 9 9.0
10 10 9.0
29 11 13.5
29 12 13.5
29 13 13.5
29 14 13.5
29 15 13.5
get_new_theta(msg, theta, time)
返回列表(new_theta, new_time)
的元组。 zip(*get_new_theta(msg, theta, time))
给出了元组(theta, time)
上的迭代器