就地将 None 替换为 Null
我需要把我的测试结果放到一个csv文件里,以便进行报告。在我的Python测试代码中,当没有值的时候,我的变量会用Python的方式填充为None。
现在有人让我把这些None替换成“Null”,这样在生成报告的时候能用上。我觉得这应该很简单,可能已经被解决过很多次了。
这是我写的代码:
for field in (TestCase.productUnderTest,TestCase.versionUnderTest,TestCase.name,TestCase.results,TestCase.lastTestEnd,TestCase.parent,TestCase.level):
if field == None:
field = 'Null'
ME.csvoutput.write("%s,%s,%s,%s,%s,%s,%s\n" % (TestCase.productUnderTest,TestCase.versionUnderTest,TestCase.name,TestCase.results,TestCase.lastTestEnd,TestCase.parent,TestCase.level))
可惜的是,这段代码只在for循环的范围内改变了字段。我该怎么做才能在写入语句的范围内也改变它呢?
(其实我很乐意直接写“Null”,而不去改变我的变量,不过我两种方式都可以。)
4 个回答
0
为了保存你的代码,你可以试试:
for field_name in ('productUnderTest','versionUnderTest','name','results','lastTestEnd','parent','level'):
if getattr(TestCase, field_name) is None:
setattr(TestCase, 'Null')
我建议你看看csv这个模块。
0
这样做:
fields = [str(field) or "Null" for field in (TestCase.productUnderTest,TestCase.versionUnderTest,TestCase.name,TestCase.results,TestCase.lastTestEnd,TestCase.parent,TestCase.level)]
ME.csvoutput.write("%s\n" % ",".join(fields))))
或者,更强大一点:使用生成器对象:
fields = (str(field) or "Null" for field in (TestCase.productUnderTest,TestCase.versionUnderTest,TestCase.name,TestCase.results,TestCase.lastTestEnd,TestCase.parent,TestCase.level))
2
在编程中,有时候我们需要让程序在特定的条件下执行某些操作。这就像给程序设定了一些规则,只有当这些规则被满足时,程序才会继续进行。
比如说,你可能希望程序在用户输入正确的密码后才能打开一个文件。这个过程就需要用到条件判断。条件判断就像是在问:“如果这个条件成立,我就做这件事;如果不成立,我就做另一件事。”
在代码中,条件判断通常用一些特定的语法来实现。我们可以用“if”语句来检查条件,然后根据条件的结果来决定接下来要执行的代码。
总之,条件判断是让程序根据不同情况做出不同反应的重要工具。掌握了这个概念,你就能让你的程序变得更加智能和灵活。
result = [TestCase.productUnderTest,TestCase.versionUnderTest,TestCase.name,TestCase.results,TestCase.lastTestEnd,TestCase.parent,TestCase.level]
result = map(lambda x:x==None and 'Null' or str(x), result)
ME.csvoutput.write(",".join(result)+'\n')