如何删除列表中的特定值?

2024-09-28 19:24:26 发布

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

我有一个列表,如下所示:

my_list = 
[['UK', 'Manchester City', 'Blue', '1','2','B'],
['ES', 'FC Barcelona', 'Blue', '2','1','C'], 
['IT', 'Juventus', 'White', '3','2','A'],
['DE', 'Borussia Dortmund', 'Yellow', '4','1','A']] 

现在我想编辑my_list,并实际删除索引0345中的值

这是我的预期输出:

  my_list = 
[['Manchester City', 'Blue'],
['FC Barcelona', 'Blue'], 
['Juventus', 'White'],
['Borussia Dortmund', 'Yellow']] 

这是我尝试的代码:

for list in my_list:
    for idx in [0,3,4,5]:
        del list[idx]       
        
print(my_list) 

这是我得到的输出:

IndexError: list assignment index out of range

Tags: incityformybluelistfcwhite
1条回答
网友
1楼 · 发布于 2024-09-28 19:24:26

试一试

my_list = [['UK', 'Manchester City', 'Blue', '1', '2', 'B'],
           ['ES', 'FC Barcelona', 'Blue', '2', '1', 'C'],
           ['IT', 'Juventus', 'White', '3', '2', 'A'],
           ['DE', 'Borussia Dortmund', 'Yellow', '4', '1', 'A']]

new_list = [lst[1:3] for lst in my_list]
print(new_list)

输出

[['Manchester City', 'Blue'], ['FC Barcelona', 'Blue'], ['Juventus', 'White'], ['Borussia Dortmund', 'Yellow']]

相关问题 更多 >