Python 替换列表中的 None 值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19363881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:33:29  来源:igfitidea点击:

Replace None value in list?

pythonlistreplace

提问by user7172

I have:

我有:

d = [1,'q','3', None, 'temp']

I want to replace None value to 'None' or any string

我想将 None 值替换为 'None' 或任何字符串

expected effect:

预期效果:

d = [1,'q','3', 'None', 'temp']

a try replace in string and for loop but I get error:

尝试在字符串和 for 循环中替换,但出现错误:

TypeError: expected a character buffer object

采纳答案by Martijn Pieters

Use a simple list comprehension:

使用简单的列表理解:

['None' if v is None else v for v in d]

Demo:

演示:

>>> d = [1,'q','3', None, 'temp']
>>> ['None' if v is None else v for v in d]
[1, 'q', '3', 'None', 'temp']

Note the is Nonetest to match the Nonesingleton.

注意is None匹配None单例的测试。

回答by K DawG

Using a lengthy and inefficient however beginner friendlyfor loop it would look like:

使用冗长且低效但对初学者友好的for 循环,它看起来像:

d = [1,'q','3', None, 'temp']
e = []

for i in d:
    if i is None: #if i == None is also valid but slower and not recommended by PEP8
        e.append("None")
    else:
        e.append(i)

d = e
print d
#[1, 'q', '3', 'None', 'temp']

Only for beginners, @Martins answer is more suitable in means of power and efficiency

仅针对初学者,@Martins 的回答在功率和效率方面更适合

回答by Abhijit

List comprehension is the right way to go, but in case, for reasons best known to you, you would rather replace it in-place rather than creating a new list (arguing the fact that python list is mutable), an alternate approach is as follows

列表理解是正确的方法,但如果出于您最了解的原因,您宁愿就地替换它而不是创建新列表(认为 python 列表是可变的),另一种方法是跟随

d = [1,'q','3', None, 'temp', None]
try:
    while True:
        d[d.index(None)] = 'None'
except ValueError:
    pass

>>> d
[1, 'q', '3', 'None', 'temp', 'None']

回答by Saullo G. P. Castro

You can simply use mapand convert all itemsto strings using the strfunction:

您可以使用以下函数简单地使用所有项目map并将其转换为字符串:str

map(str, d)
#['1', 'q', '3', 'None', 'temp']

If you only want to convert the Nonevalues, you can do:

如果您只想转换None值,您可以执行以下操作:

[str(di) if di is None else di for di in d]

回答by Uzzy

Starting Python 3.6 you can do it in shorter form:

从 Python 3.6 开始,您可以以更短的形式进行:

d = [f'{e}' for e in d]

hope this helps to someone since, I was having this issue just a while ago.

希望这对某人有所帮助,因为不久前我遇到了这个问题。