ine*_*tom 10 python python-3.x python-3.3
我有一个列表,其中是另一个列表,我想 doc.write(a)
a = [[1, 2, "hello"],
[3, 5, "hi There"],
[5,7,"I don't know"]]
doc.write(''.join(a))
TypeError: sequence item 0: expected str instance, list found
Run Code Online (Sandbox Code Playgroud)
我该如何处理这个问题,是否必须创建一个我加入的for循环并添加所有子列表?
真正的目标是使它在某种程度上可以用于人类的可读性,但我不想要你的完成解决方案.
ars*_*jii 13
你可以尝试类似的东西
>>> a = [[1, 2, "hello"],[3, 5, "hi There"],[5,7,"I don't know"]]
>>>
>>> ''.join(str(r) for v in a for r in v)
"12hello35hi There57I don't know"
Run Code Online (Sandbox Code Playgroud)
即
doc.write(''.join(str(r) for v in a for r in v))
Run Code Online (Sandbox Code Playgroud)
您可以做多种合法的事情,并且在不知道您想要哪一项的情况下,任何人都无法说哪一项是正确的。
\n\n首先,您可以只写stror reprof a:
>>> a=[[1, 2, "hello"],[3, 5, "hi There"],[5,7,"I don\'t know"]]\n>>> repr(a)\n\'[[1, 2, \\\'hello\\\'], [3, 5, \\\'hi There\\\'], [5, 7, "I don\\\'t know"]]\'\nRun Code Online (Sandbox Code Playgroud)\n\n请注意,这就是它的print作用(它会打印str您给它的任何内容\xe2\x80\x94,尽管使用列表, thestr与 相同repr;它们都是有效的\'[\' + \', \'.join(map(repr, self)) + \']\')。
其次,您可以使用专为持久数据设计的格式,例如 JSON:
\n\n>>> json.dumps(a)\n\'[[1, 2, "hello"], [3, 5, "hi There"], [5, 7, "I don\\\'t know"]]\'\nRun Code Online (Sandbox Code Playgroud)\n\na第三,您可以以您选择的某种方式将每个元素的表示连接在一起,这对于 amap或 a 理解式来说是微不足道的。例如:
>>> \'[\' + \', \'.join(map(repr, a)) + \']\'\n\'[[1, 2, \\\'hello\\\'], [3, 5, \\\'hi There\\\'], [5, 7, "I don\\\'t know"]]\'\nRun Code Online (Sandbox Code Playgroud)\n\n\xe2\x80\xa6\xc2\xa0 或 \xe2\x80\xa6
\n\n>>> \'My stuff includes: \' + \',\'.join(map(repr, a)) + \'\\n\'\n\'My stuff includes: [1, 2, \\\'hello\\\'],[3, 5, \\\'hi There\\\'],[5, 7, "I don\\\'t know"]\\n\'\nRun Code Online (Sandbox Code Playgroud)\n\n或者你可以递归地做同样的事情。
\n\n或者,您可以展平列表(例如,使用 一步展平它itertools.chain,或者使用文档中的食谱itertools或包递归more-itertools地展平列表),然后根据需要对各个部分进行字符串化,然后将它们连接起来。
或者你可以只写这个词LIST。
所有这些都是完全有效的传递给 的东西write。
| 归档时间: |
|
| 查看次数: |
18812 次 |
| 最近记录: |