单行块重新分配 [英] Single line chunk re-assignment

查看:48
本文介绍了单行块重新分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如以下代码所示,我有一个块列表 x 和完整列表 h.我想将存储在 x 中的值重新分配回 h 的正确位置.

As shown in the following code, I have a chunk list x and the full list h. I want to reassign back the values stored in x in the correct positions of h.

index = 0
for t1 in range(lbp, ubp):
   h[4 + t1] = x[index]
   index = index + 1

有谁知道如何用单行/表达式来写它?

Does anyone know how to write it in a single line/expression?

免责声明:这是一个更大项目的一部分,我尽可能地简化了问题.您可以期望矩阵大小是正确的,但如果您认为我遗漏了什么,请询问.对于测试,您可以使用以下变量值:

Disclaimer: This is part of a bigger project and I simplified the questions as much as possible. You can expect the matrix sizes to be correct but if you think I am missing something please ask for it. For testing you can use the following variable values:

h = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x = [20, 21]
lbp = 2
ubp = 4

推荐答案

您可以使用切片分配在左侧展开并将您的 x 列表直接分配给 的索引h,例如:

You can use slice assignment to expand on the left-hand side and assign your x list directly to the indices of h, e.g.:

h = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x = [20, 21]
lbp = 2
ubp = 4     
h[4 + lbp:4 + ubp] = x  # or better yet h[4 + lbp:4 + lbp + len(x)] = x
print(h)
# [1, 2, 3, 4, 5, 6, 20, 21, 9, 10]

我不太确定为什么要在循环中的索引中添加 4 或者 lbpubp 应该是什么意思,寿.请记住,当您选择这样的范围时,您分配给该范围的列表的长度必须与该范围相同.

I'm not really sure why are you adding 4 to the indexes in your loop nor what lbp and ubp are supposed to mean, tho. Keep in mind that when you select a range like this, the list you're assigning to the range has to be of the same length as the range.

这篇关于单行块重新分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆