Python通过数组中的循环逐个插入值

2024-04-25 23:57:57 发布

您现在位置:Python中文网/ 问答频道 /正文

[更新:修复了PHP和Python代码中的一些错误]

我有一个简单的要求。在PHP中,我可以通过简单地这样写$sample[10] = "Sample"来声明插入值的索引。要插入多个值,我将创建一个for循环,其中每个循环中都将在数组中插入一个值。下面是该代码的一个示例,但在我基于拆分字符串数组长度的循环时做了一些修改:

$toexp = str_split("Hello World");
$array = array();
for ($x = 0; $x < count($toexp); $x++){
    $array[$x] = $toexp[$x]; //sample value only
    echo $array[$x];
}

我试图用Python创建类似的代码

samplearray = []
splits = list("Hello World")
for p in splits:
    samplearray.extend(p)
    print(samplearray[1])

但是,会弹出一个错误:

print(samplearray[1])
IndexError: list index out of range

这是否意味着该值仅在索引0处插入?如果我打印samplearray[0],则不会发生错误,它会打印出该索引中的值。请向我解释如何将代码从PHP复制到Python。提前谢谢你


Tags: sample代码helloforworld错误数组array
1条回答
网友
1楼 · 发布于 2024-04-25 23:57:57

extend从迭代器扩展数组,在本例中,迭代器不是您想要的。与PHP不同,Python不允许在数组中插入超过末尾的任意元素。但是,由于总是在数组末尾插入,因此可以使用append方法添加额外的元素:

samplearray = []
x = 0
for p in "Hello world":
    samplearray.append(x + 1)
    print(samplearray[x])
    x += 1

相关问题 更多 >