首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将python列表转换为tsv格式,以便在memsql中输入

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

Stack Overflow用户
提问于 2018-08-04 22:06:26
回答 1查看 104关注 0票数 -1

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

代码语言:javascript
复制
[1518785613920, 1, 19, 3099, 'abc', 0, 'def']

我想要下面的格式。我试着使用循环,但它从字符串中删除了单引号。对于join,它还删除了单引号。

代码语言:javascript
复制
1518785613920, 1, 19, 3099, 'abc', 0, 'def'
EN

回答 1

Stack Overflow用户

发布于 2018-08-04 23:22:51

在显示列表中的字符串时,python显示的“单引号”只是"this is a string“的标记。如果你需要它们作为输出,你可以简单地在你的字符串本身中添加单号-然后它会用双号来显示:

代码语言:javascript
复制
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=","

输出:

代码语言:javascript
复制
[1, "'some data'", 2, 4] 
1, 'some data', 2, 4

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

代码语言:javascript
复制
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=", ")

输出:

代码语言:javascript
复制
 1518785613920, 1, 19, 3099, 'abc', 0, 'def'

如果你想把它写到一个文件中,你可以像这样构造一个输出:

代码语言:javascript
复制
# 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所提到的,这与

代码语言:javascript
复制
s = repr(data).strip("[]")

Doku for print()

Doku for join()或搜索SO,f.e.这里:What exactly does the .join() method do?

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51686386

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档