繁体   English   中英

Python-更改列表中的项目值

[英]Python - Change item value in list

我使用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)]

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

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

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

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

我引用了其他一些包括该线程在内的stackoverflow线程,但无法使用它: 查找和替换列表中的元素(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', '-', '-')]

首先,您尝试更改元组中的元素,但是元组是不可变的对象。
“更改”它们的唯一方法是在现有的基础上创建

其次,这部分代码

for thing in items:
    if thing == None:
        thing = '-'

仅替换的变量内容thing ,所以即使你会在你的可变对象zipped_up列表-如(嵌套)名单-你的代码不会无论如何改变它们

因此,如果您出于某种原因不想接受sacul解决方案,而是编辑循环方法,则可以将新创建的元组追加到新的空列表中。

如下面的代码(不是很好):

result = []
for a, b, c in zipped_up:
    a = '-' if a is None else a
    b = '-' if b is None else b
    c = '-' if c is None else c
    result.append((a, b, c))

print(result)

输出:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM