Skip to main content
 首页 » 编程设计

python之替换嵌套列表中某些列表中的值

2025年01月19日11zhujiabin

我正在为蜡笔制造商编写程序。他们有 4 包库存(目前是调试的良好起点)。我已在列表中显示:

colors=[['pink','green','blue'],['blue','green','red'],['pink',blue','yellow'],['orange','pink','yellow']] 

我想改变中间绿色的两包蜡笔的颜色,以获得颜色更多样的包。 首先我找到所有中间有绿色的包:

packsfound = [] 
 
for pack in colors: 
 if pack[1]=="green": 
     packsfound.append(pack) 
 
print("packs with one:",packsfound) 

然后我从库存(颜色)中取出我选择的包,以便可以修改它们并稍后放回原处。

try: 
 for pack in packsfound: 
  colors.remove(pack) 
except Exception as e: 
  print(e) 
  pass  

然后我做替换:

for pack in packsfound: 
try: 
 for i, color in enumerate(packsfound): 
     position=color.index("green") 
     print("replace at:",position) 
     break 
 
 pack[position]="yellow" 
 print("replaced rows:",packsfound) 
except Exception as e: 
 print(e) 
 pass  

然后我将修改后的列表附加回颜色,以便它们是新的库存

try: 
 for pack in packsfound:         
  colors.append(pack) 
except Exception as e: 
  print(e) 
  pass 
 
print(colors) 

问题是它只遍历第一个列表并替换第一个绿色。然后程序说绿色不在列表中并且不会替换第二个绿色:

packs with one: [['pink', 'green', 'blue'], ['blue', 'green', 'red']] 
replace at: 1 
replaced rows: [['pink', 'yellow', 'blue'], ['blue', 'green', 'red']] 
'green' is not in list 
[['pink', 'blue', 'yellow'], ['orange', 'pink', 'yellow'], ['pink', 'yellow', 'blue'], ['blue', 'green', 'red']] 

我已经尝试了很多事情,比如移动 try 和 except 以及将替换行移入和移出循环,添加 break 和 pass 但没有任何效果。

请您参考如下方法:

替换循环有错误。你放置 break 语句的方式只允许循环的一次迭代。你可以使用这个循环:

for pack in packsfound: 
    try: 
        position = pack.index('green') 
        print("replace at:",position) 
        pack[position]="yellow" 
        print("replaced rows:",packsfound) 
except Exception as e: 
        print(e) 
        pass