Skip to main content
 首页 » 编程设计

Python之更改列表中的项目值

2025年05月04日13haluo1

我有一些使用 itertools.zip_longest 压缩在一起的数据

import itertools 
names = 'Tim Bob Julian Carmen Sofia Mike Kim Andre'.split() 
locations = 'DE ES AUS NL BR US'.split() 
confirmed = [False, True, True, False, True] 
zipped_up = list(itertools.zip_longest(names, locations, confirmed)) 

如果我按现在的方式打印 zipped_up,我会得到以下信息:

[('Tim', 'DE', False), ('Bob', 'ES', True),  
('Julian','AUS', True), ('Carmen', 'NL', False),  
('Sofia', 'BR',True), ('Mike', 'US', None),  
('Kim',None, None),('Andre', None, None)] 

这很好,缺失值默认为“无”。 现在我想将“无”值更改为“-”。

看来我应该能够在下面的嵌套循环中这样做。如果我在下面的代码中包含一个 print 语句,它似乎一切都按照我想要的方式工作:

for items in zipped_up: 
    for thing in items: 
        if thing == None: 
            thing = '-' 
        print(thing) 

但是如果我再次打印 zipped_up(在循环外),“无”值没有改变。为什么不?是否与列表项的数据类型有关,即元组?

我已经引用了一些其他的 stackoverflow 线程,包括这个,但一直无法使用它: finding and replacing elements in a list (python)

请您参考如下方法:

只需使用 fillvalue 参数:

zipped_up = list(itertools.zip_longest(names, locations, confirmed, fillvalue='-')) 
 
>>> zipped_up 
[('Tim', 'DE', False), ('Bob', 'ES', True), ('Julian', 'AUS', True), ('Carmen', 'NL', False), ('Sofia', 'BR', True), ('Mike', 'US', '-'), ('Kim', '-', '-'), ('Andre', '-', '-')]