Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 更换'';带有';0';_Python_String_Csv_Null - Fatal编程技术网

Python 更换'';带有';0';

Python 更换'';带有';0';,python,string,csv,null,Python,String,Csv,Null,我有一些.csv文件,其中包含NULL值,这些值在表中被视为空。例如: ID Volts Current Watts 0 383 0 1 383 1 383 2 382 2 764 此.csv文件被输入到我的程序中,并转换为如下列表: with open(inputPath + file) as inFile: csvFile = csv.reader(inFile) fo

我有一些
.csv
文件,其中包含
NULL
值,这些值在表中被视为空。例如:

ID   Volts   Current   Watts
0    383               0
1    383     1         383
2    382     2         764
.csv
文件被输入到我的程序中,并转换为如下列表:

with open(inputPath + file) as inFile:
    csvFile = csv.reader(inFile)
    for row in csvFile:
        removeNull(row)
        print(row)
这实际上是将
csvFile
中的每一行转换为如下所示的值列表:

with open(inputPath + file) as inFile:
    csvFile = csv.reader(inFile)
    for row in csvFile:
        removeNull(row)
        print(row)
['0'、'383'、'0']
['1'、'383'、'1'、'383]

请注意,
NULL
值现在只是空字符串,
'

然后,关于上述程序的snipet,
removeNull()
定义为:

def removeNull(row):
    nullIndex = row.index('')
    row.remove('')
    newRow = row.insert(nullIndex, '0')
    return newRow
它在列表(又名行)中查找空字符串,
'
,并将其索引注释为
nullIndex
。然后删除所述索引处的空字符串,将其替换为
'0'
,并返回已编辑的列表

问题:我的
removeNull()
函数导致它只替换列表中的第一个空字符串
'
,它到底出了什么问题?我如何修复它,使其适用于列表中的所有空字符串

为了澄清,像这样一个表,每行只有一个
NULL
值,或者转换为列表后为空字符串,就可以正常工作了

ID   Volts   Current   Watts
0    383               0
1    383     1         383
2    382     2         764
['0','383','0']
工作正常

但是,如果我有一个这样的表,每行有多个
NULL
值,它将只替换转换列表中的第一个空字符串,而不处理其余的字符串

ID   Volts   Current   Watts
0                      0
1    383     1         383
2    382     2         764

['0','','0']
无法正常工作。

因为
list.index
只返回列表中第一次出现的项的索引。您可以在每一行上使用列表来替换:

def removeNull(row):
    return ['0' if i=='' else i for i in row]
    #       |<- ternary op. ->|  

因为
list.index
只返回列表中第一次出现的项的索引。您可以在每一行上使用列表来替换:

def removeNull(row):
    return ['0' if i=='' else i for i in row]
    #       |<- ternary op. ->|  

newRow=row.insert(…)
在我看来很可疑<代码>行。insert应返回
None
。不需要单独的函数。只需在循环中添加一行:
用于csvFile中的行:row=[item if item else'0'用于行中的项]
@StevenRumbalski正如我上面所说的,这不是很明显,但我需要为程序的其他元素提供单独的函数。不过,您的答案是完全正确的,所以不管怎样,谢谢您。
newRow=row.insert(…)
看起来有点可疑<代码>行。insert应返回
None
。不需要单独的函数。只需在循环中添加一行:
用于csvFile中的行:row=[item if item else'0'用于行中的项]
@StevenRumbalski正如我上面所说的,这不是很明显,但我需要为程序的其他元素提供单独的函数。然而,你的答案是完全正确的,所以不管怎样,谢谢你。