gpt4 book ai didi

python - 替换python中列表之间的元素

转载 作者:太空宇宙 更新时间:2023-11-04 07:43:04 35 4
gpt4 key购买 nike

我目前正在尝试用另一个列表中的元素替换 2D 列表中的元素,以实现我在 python 中制作的游戏。这是我目前所拥有的:

listA = [1, 3, 5]
listB = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

for a in range(len(listA)):
alpha = (a/3) #number of rows in listB
beta = (a/3) #number of columns in listB
listB[alpha][beta] = 123

当我这样做时,我得到了

[[123, 123, 123], [0, 0, 0], [0, 0, 0]] 

而不是我想要的给定参数,

[[0, 123, 0], [123, 0, 123], [0, 0, 0]]

我做错了什么吗?

最佳答案

而不是使用 for a in range(len(listA)): 遍历 listA 的索引,您应该使用 for a in listA: 遍历 listA 的元素

假设 A 中的索引像这样转换为 B 中的坐标:

0 1 2
3 4 5
6 7 8

然后是beta,也就是B的列对应a , 应计算为 a%3 , 而不是 a/3 .

listA = [1, 3, 5]
listB = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

for a in listA:
#two slashes is integer division, not a comment,
#despite markup's color scheme
alpha = a//3
beta = a%3
listB[alpha][beta] = 123

print listB

输出:

[[0, 123, 0], [123, 0, 123], [0, 0, 0]]

关于python - 替换python中列表之间的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15227744/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com