python - Python 中的特定范围后不出现值

标签 python for-loop

我有一些代码旨在更新 5 个元素中每个元素的“时间”值。但是,当该值达到 15 时,其后面的值将不再计算在内。这是代码:

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,16,17,18]
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
58 16 18 <-- the values after 15 do not print
58 17 18

需要此论坛的帮助。谢谢。

最佳答案

问题是你的循环没有走那么远。请注意,new_theta 有 4 个值,您返回其中的 3 个值。外部循环 for i, (theta, time) ... 执行 3 次,内部循环 for j in range(5)... 每个执行 5 次其中 3 次,总共 15 次迭代。这就是为什么最后打印的数字是 15。

在这种情况下,修复方法并不明显,取决于您想要做什么。通过将外部循环修改为运行 4 次并修改内部循环以在第 19 次运行时退出(因为您没有完整的 5 条消息可供迭代),以下代码至少可以无错误地遍历所有 18 个值。

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, new_time

msg = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
theta = 1
time = 4.5

for i, (theta, time) in enumerate( zip(*get_new_theta(msg, theta, time)) ):
    for j in range(5):
        if i*5+j >= len(msg):
            break
        print(theta, msg[i*5+j], time)

关于python - Python 中的特定范围后不出现值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52091059/

相关文章:

python - 查询变换球体上的最近点

python - 如何验证我的 SSL 证书是否不和谐?

python - 在数据框/二维数组中查找元组的行平均值

C++ 相当于 .ToString()

c - 开发一个函数,返回数组中存在的不同值的数量

python - Whatsapp 自动机器人无法在 WhatsApp 联系人列表中搜索

c++ - For 循环条件(整数 vector )。如何获取之前的值?

matlab - 使用一组开始和结束索引索引数组

r - 如何加速或矢量化 for 循环?

python - 使用 Canny edge 创建 mask - 已更新