繁体   English   中英

将python列表转换为tsv格式以在memsql中输入

[英]convert python list to tsv format for input in memsql

我正在尝试将以下列表转换为tsv格式。

[1518785613920, 1, 19, 3099, 'abc', 0, 'def']

我想要以下格式。 我尝试使用循环,但它从字符串中删除了单引号。 使用join也可以删除单引号。

1518785613920, 1, 19, 3099, 'abc', 0, 'def'

当向您显示列表内的字符串只是“这是一个字符串”的标记时,将显示“单引号” python。 如果需要它们作为输出,则可以简单地将单引号添加到字符串本身-然后将以双引号显示:

print([1,"'some data'",2,4))            # no deref, will be printed as repr(list).
print(*[1,"'some data'",2,4], sep=", ") # *[..] will deref elements+ print each with sep=","

输出:

[1, "'some data'", 2, 4] 
1, 'some data', 2, 4

您可以简单地在输出中包括单个刻度:

data = [1518785613920, 1, 19, 3099, 'abc', 0, 'def']

# generator expression that adds '' around strings in the generator and prints it 
# using the deref * and print's sep=", " specifier
print( *(x if not isinstance(x,str) else "'{}'".format(x) for x in data), sep=", ")

输出:

 1518785613920, 1, 19, 3099, 'abc', 0, 'def'

如果要将其写入文件,可以构造如下输出:

# use join() and some generator comp to create output. join needs strings so str(int)
s = ', '.join((str(x) if not isinstance(x,str) else "'{}'".format(x) for x in data))
# s is identical to above output

正如MadPhysicist提到的那样

s = repr(data).strip("[]")

用于print() Doku print()
Doku for join()或搜索SO,例如: .join()方法到底做什么?

您可能要使用csv.writer

  1. 随附标准库
  2. 用字符串中的引号覆盖各种边缘情况

io.StringIO一起,它将允许您构建内存字符串,您可以进一步传递该字符串。

暂无
暂无

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

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