简体   繁体   English

使用if条件列出理解

[英]List comprehension with if-condition

The following line of Python code 以下Python代码行

values = ", ".join(["\"%s\"" % x for x in row])

takes a list of elements in "row" to create a comma-separated string "values", while each value is put in double quotes, eg: "New York", "5", "", "3.2" 获取“row”中的元素列表以创建逗号分隔的字符串“values”,而每个值都放在双引号中,例如:“New York”,“5”,“”,“3.2”

However, since the result is to be part of a mysqldump file, empty fields ("") should become NULL (without double quotes). 但是,由于结果是mysqldump文件的一部分,空字段(“”)应该变为NULL(不带双引号)。

Therefore, I'd like to learn how to change that expression so that it is checked whether x is empty (""), in which case NULL should be appended to the values string. 因此,我想学习如何更改该表达式,以便检查x是否为空(“”),在这种情况下,NULL应该附加到值字符串。

Thanks 谢谢

values = ", ".join('"%s"' % x if x else 'NULL' for x in row)

For example: 例如:

>>> row = ["foo", "", "bar"]
>>> values = ", ".join('"%s"' % x if x else 'NULL' for x in row)
>>> values
'"foo", NULL, "bar"'

Thanks to DSM for pointing out that it's of course even better to change the list comprehension into a generator expression - this makes it faster because it's no longer necessary to construct a list that will be discarded immediately afterwards. 感谢DSM指出将列表理解更改为生成器表达式当然更好 - 这使得它更快,因为不再需要构建一个将在之后立即丢弃的列表。

values = ", ".join(["NULL" if x == "" else "\"%s\"" % x for x in row])

To make this a bit more robust, I'd utilise the csv module to handle embedded field and string delimiters... (just an adhoc example) 为了使这更加健壮,我将利用csv模块来处理嵌入字段和字符串分隔符...(只是一个特殊的例子)

from StringIO import StringIO
import csv

csvrec = StringIO()
csvout = csv.writer(csvrec, quoting=csv.QUOTE_ALL)
items = [1, 'hello, there, how are you?', 3.2, 'it\'s a "cat" I say!', '', '']
csvout.writerow([col or '\t' for col in items]) # maybe col != '' ?
print csvrec.getvalue().replace('"\t"', 'NULL').strip()
# "1","hello, there, how are you?","3.2","it's a ""cat"" I say!",NULL,NULL

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

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