简体   繁体   English

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

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

I am trying to convert below list to tsv format. 我正在尝试将以下列表转换为tsv格式。

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

I want below format. 我想要以下格式。 I tried to do using loop but it's removing single quotes from Strings. 我尝试使用循环,但它从字符串中删除了单引号。 With join also it is removing single quotes. 使用join也可以删除单引号。

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

The "single quotes" python is displaying when showing you the strings inside a list are just markers for "this is a string". 当向您显示列表内的字符串只是“这是一个字符串”的标记时,将显示“单引号” python。 If you need them as output, you can simply add singleticks to your string itself - it will then be displayed with doubleticks: 如果需要它们作为输出,则可以简单地将单引号添加到字符串本身-然后将以双引号显示:

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=","

Output: 输出:

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

You can simply include the single ticks in your output: 您可以简单地在输出中包括单个刻度:

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=", ")

Output: 输出:

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

If you want to write it into a file, you can construct an output like so: 如果要将其写入文件,可以构造如下输出:

# 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

As mentioned by MadPhysicist thats about the same as 正如MadPhysicist提到的那样

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

Doku for print() 用于print() Doku print()
Doku for join() or search SO, fe here: What exactly does the .join() method do? Doku for join()或搜索SO,例如: .join()方法到底做什么?

You probably want to use csv.writer which: 您可能要使用csv.writer

  1. Comes with the standard library 随附标准库
  2. Covers various edge-cases with quotes in your strings 用字符串中的引号覆盖各种边缘情况

Together with io.StringIO it will allow you to build in-memory string which you can pass further. io.StringIO一起,它将允许您构建内存字符串,您可以进一步传递该字符串。

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

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