Tho*_*ind 0 python csv string null
我有一些.csv文件包含NULL在表中被视为空的值.例如:
ID Volts Current Watts
0 383 0
1 383 1 383
2 382 2 764
Run Code Online (Sandbox Code Playgroud)
此.csv文件输入到我的程序中并转换为如下列表:
with open(inputPath + file) as inFile:
csvFile = csv.reader(inFile)
for row in csvFile:
removeNull(row)
print(row)
Run Code Online (Sandbox Code Playgroud)
它基本上将每一行放入csvFile并将其转换为值列表,如下所示:
['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
Run Code Online (Sandbox Code Playgroud)
通过列表(aka行)查找空字符串'',并将其索引记录为nullIndex.然后删除所述索引处的空字符串,将其替换为'0'并返回编辑后的列表.
问题:我的removeNull()函数究竟出了什么问题导致它只替换列表中的第一个空字符串''?我如何修复它以便它适用于列表中的所有空字符串?
为了澄清,像这样的表,每行只有一个 NULL值,或者一旦转换为列表,空字符串就可以正常工作.
ID Volts Current Watts
0 383 0
1 383 1 383
2 382 2 764
Run Code Online (Sandbox Code Playgroud)
['0', '383', '', '0'] 工作良好.
但是,如果我有一个这样的表,每行有多个 NULL值,它将只替换转换列表中的第一个空字符串,并且不执行任何其他操作.
ID Volts Current Watts
0 0
1 383 1 383
2 382 2 764
Run Code Online (Sandbox Code Playgroud)
['0', '', '', '0'] 不行.
因为list.index只返回列表中第一次出现的索引.您可以改为在每行上使用列表推导来进行替换:
def removeNull(row):
return ['0' if i=='' else i for i in row]
# |<- ternary op. ->|
Run Code Online (Sandbox Code Playgroud)
在三元运算符列表中的理解与替换字符串的空白'0',同时为他们返回等.
另外,您的函数不会row 就地修改,因此,您需要将函数的返回值赋值为row:
for row in csvFile:
row = removeNull(row)
print(row)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1696 次 |
| 最近记录: |