被阵列卡住了

2024-04-20 15:14:17 发布

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

假设您有一个长度为10的Python列表(数组),其中最后3个单元格不包含任何内容,其他单元格有其他内容

下面的代码是否将a的第5个单元格的内容复制到数组a末尾之后的所有单元格,并将a的第5个单元格的内容替换为“20”,或者我错了

for in in range (len(a)-1, 4, -1):
    a[i+i] = a[i]
a[4] = 20

2条回答

如果我理解正确,您希望将a[6]的值复制到数组的所有以下索引a,您可以使用以下方法执行此操作

# create the array you mention, some values up to index 6 then three None
a = [f for f in range(0,10)]
a[7] = a[8] = a[9] = None
print(a)
# [0, 1, 2, 3, 4, 5, 6, None, None, None]

# we copy the value of a[6] to the rest
for i in range(6, len(a) -1):
    a[i+1] = a[i]

print(a)
# [0, 1, 2, 3, 4, 5, 6, 6, 6, 6]

但是,如果要用值6替换数组中的所有值None,可以这样做

# create the array you mention, some values up to index 6 then three None
a = [f for f in range(0,10)]
a[7] = a[8] = a[9] = None
# replace all None values by 6 and reassign a
a = [6 if v is None else v for v in a]
print(a)

这是你想做的吗

a = [1, 2, 3, 4, 5, 6, 7, None, None, None]
for i in range (len(a)-1, 4, -1):
    a[i] = a[4]
a[4] = 20
print (a) #=> [1, 2, 3, 4, 20, 5, 5, 5, 5, 5]

相关问题 更多 >