从 Python 中的列表列表打印到文件
我正在尝试打印到一个如下所示的文件:
'A'
'1'
'B'
'2'
'C'
'3'
然而,给出下面的代码,结果是:
['A']
['B']
['C']
这可能是一个“垒球”问题,但是我在这里做错了什么?
l1 = ['1']
l2 = ['A']
l3 = ['2']
l4 = ['B']
l5 = ['3']
l6 = ['C']
listoflists = [l1,l2,l3,l4,l5,l6]
itr = iter(listoflists)
f = open ('order.txt','w')
while True:
try:
itr.next()
s = str(itr.next())
f.write(str('\n'))
f.write(s)
except StopIteration:
break
f.close()
I am trying to print to a file that will look like:
'A'
'1'
'B'
'2'
'C'
'3'
Given the code below, however, the result is :
['A']
['B']
['C']
This is probably a 'softball' question, but what am I doing wrong here?
l1 = ['1']
l2 = ['A']
l3 = ['2']
l4 = ['B']
l5 = ['3']
l6 = ['C']
listoflists = [l1,l2,l3,l4,l5,l6]
itr = iter(listoflists)
f = open ('order.txt','w')
while True:
try:
itr.next()
s = str(itr.next())
f.write(str('\n'))
f.write(s)
except StopIteration:
break
f.close()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
首先,不要使用
iter
和next()
,这就是for
的用途。其次,您实际上是将列表写入文件,而不是其内容。因此,您可以打印列表的第一个元素(即l1[0]
)或迭代所有内部列表元素。您的代码应如下所示:
First of all, don't use
iter
andnext()
, that's whatfor
is for. Secondly, you are actually writing a list to the file, not its contents. So you could either print the first element of the list (i.e.l1[0]
) or iterate through all the inner lists elements.Your code should look like this:
我认为解决这个问题的最好方法就是使用基本的嵌套循环。试试这个:
Out.txt 现在包含:
哦,如果没有单行解决方案,任何 Python 问题都是不完整的(这也删除了我最初响应中的尾随逗号)。
Out.txt 现在包含:
I think the best way to solve this is just with a basic nested loop. Try this:
Out.txt now holds:
Oh, and no Python question is complete without a one-liner solution (this also removes the trailing comma from my initial response).
Out.txt now holds:
您的代码可以简单得多:
但是,这将打印类似
['1']
的内容。看起来你想要的东西更像是:另外,为什么你有一堆单元素列表?不能将所有元素放入一个列表中吗?
Your code could be a lot simpler:
But, this is going to print something like
['1']
. It seems like you want something more like:Also, why do you have a bunch of single-element lists? Couldn't you put all the elements into one list?
您获得错误文件内容的简单原因是您调用了 iter 两次。第 15-16 行是:
有关更多 Pythonic 打印语义,请参阅其他答案
The simple reason why you are getting the wrong file contents is because you are calling
iter
twice. Lines 15-16 are:For more Pythonic printing semantics, see the other answers
在输出中包含引号有点奇怪,但如果您坚持:
您没有指定如果内部列表不只有一个元素会发生什么,因此这里忽略任何其他可能性。
Including the quotes in the output is a bit odd, but if you insist:
You don't specify what will happen if the inner list does not have just one element, so any other possibility is ignored here.
您可以简单地使用
itertools.chain
迭代所有列表元素(记录为 此处):You can simply iterate through all list elements with
itertools.chain
(documented here):