python列表到换行符分隔值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3790805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python list to newline separated value
提问by m4k
Im trying to get data in pylon to use in jquery autocomplete,
the librarary i'm using for autocomplete it requires this format
我试图在 pylon 中获取数据以在 jquery 自动完成中使用,我用于自动完成的库需要这种格式
abc
pqr
xyz
and in python i have data in this format
在 python 中,我有这种格式的数据
[["abc"], ["pqr"],["xyz"]
How do i convert this list to the above one.
我如何将此列表转换为上述列表。
Edit:
I trying to use these for a autocompete and i'm using pylons, in which the query to the server return list in this format
编辑:
我尝试将这些用于自动竞争,并且我正在使用 pylons,其中对服务器的查询以这种格式返回列表
[["abc"], ["pqr"],["xyz"]
http://jquery.bassistance.de/autocomplete/demo/this library except remote call in
http://jquery.bassistance.de/autocomplete/demo/这个库除了远程调用
abc
pqr
xyz
i tried to use
我试着用
"\n".join(item[0] for item in my_list)
but it returns data in firebug like this.
但它像这样在萤火虫中返回数据。
'asd\ndad\nweq'
i want it to be in
我希望它在
abc
pqr
xyz
any help would be appreciated as i'm a PHP developer this is first time i'm trying to do code in python.
任何帮助将不胜感激,因为我是一名 PHP 开发人员,这是我第一次尝试在 python 中编写代码。
thnaks
thnaks
回答by Xzhsh
Er I'm not sure what exactly you want, but if you need to print that you could do
呃,我不确定你到底想要什么,但如果你需要打印,你可以做
for l in data:
print l[0]
or if you want to make it a flat list, you could do something like
或者如果你想让它成为一个平面列表,你可以做一些类似的事情
map(lambda x: x[0], a)
or if you even just want a single string with newlines, you could do something like
或者如果你甚至只想要一个带换行符的字符串,你可以做类似的事情
"\n".join(map(lambda x: x[0], a))
Dunno if that helped at all, but wish you luck
不知道这是否有帮助,但祝你好运
回答by Matti Virkkunen
"\n".join(item[0] for item in my_list)
However, what's this got to do with JSON...?
但是,这与 JSON 有什么关系...?
回答by Jim Brissom
I am not exactly sure what you want, but you may try:
我不确定你想要什么,但你可以尝试:
nested_list = [ ["abc"], ["pqr"], ["xyz"] ]
data = "\n".join( (item[0] for item in nested_list) )
This will convert your list of lists into a string separated by newline characters.
这会将您的列表列表转换为由换行符分隔的字符串。
回答by Shlomi Fish
I think you want this, though it's hard to know based on your description:
我想你想要这个,尽管根据你的描述很难知道:
>>> l = [["abc"],["pqr"],["xyz"]]
>>> "".join(map(lambda a:a[0] + "\n",l))
'abc\npqr\nxyz\n'
回答by Jimothy
Your code is doing what you want it to, but I imagine you're inspecting the results in the python REPL or ipython, and expecting to see new lines instead of '\n'.
您的代码正在执行您想要的操作,但我想您正在检查 python REPL 或 ipython 中的结果,并希望看到新行而不是 '\n'。
In [1]: items = [["abc"], ["pqr"],["xyz"]]
In [2]: s = "\n".join(item[0] for item in items)
In [3]: s
Out[3]: 'abc\npqr\nxyz'
In [4]: print s
abc
pqr
xyz

