简体   繁体   English

如何比较列表中的空值

[英]How to compare an empty value in a list

I have an array of string and I want to know how to add a string if some of the values is empty.我有一个字符串数组,如果某些值为空,我想知道如何添加字符串。 P. eg:例如:

array=["1","3","","7"]

With the previous array I want to save a string value in the third position of the array (2 index) because it is empty.对于前面的数组,我想在数组的第三个 position 中保存一个字符串值(2 索引),因为它是空的。 How can I probe it?我怎样才能探测它?

Code:代码:

if array[2]== ?:

What should I write instead of "?"我应该写什么而不是“?”

An empty string is equivalent to False , so you can simply do:空字符串等效于False ,因此您可以简单地执行以下操作:

if not array[2]:

You can do this quite nicely with a list comprehension in python:您可以通过 python 中的列表理解很好地做到这一点:

array=["1","3","","7"]

new_array = [x if x!="" else "replaced" for x in array]
new_array

returns返回

['1', '3', 'replaced', '7']

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

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