Skip to main content
 首页 » 编程设计

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

2025年05月04日17xxx_UU

我目前正在尝试用另一个列表中的元素替换 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]]