从 Python 中的列表列表打印到文件

发布于 2024-08-20 20:13:28 字数 536 浏览 1 评论 0原文

我正在尝试打印到一个如下所示的文件:

'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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

浅浅淡淡 2024-08-27 20:13:28

首先,不要使用 iternext(),这就是 for 的用途。其次,您实际上是将列表写入文件,而不是其内容。因此,您可以打印列表的第一个元素(即l1[0])或迭代所有内部列表元素。

您的代码应如下所示:

l1 = ['1']
l2 = ['A']
l3 = ['2']
l4 = ['B']
l5 = ['3']
l6 = ['C']

listoflists = [l1,l2,l3,l4,l5,l6]

f = open ('order.txt','w')

for inner_list in listoflists:
    for element in inner_list:
        f.write(element+'\n')

f.close()

First of all, don't use iter and next(), that's what for 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:

l1 = ['1']
l2 = ['A']
l3 = ['2']
l4 = ['B']
l5 = ['3']
l6 = ['C']

listoflists = [l1,l2,l3,l4,l5,l6]

f = open ('order.txt','w')

for inner_list in listoflists:
    for element in inner_list:
        f.write(element+'\n')

f.close()
北城挽邺 2024-08-27 20:13:28

我认为解决这个问题的最好方法就是使用基本的嵌套循环。试试这个:

l1 = ['1']
l2 = ['A']
l3 = ['2']
l4 = ['B']
l5 = ['3']
l6 = ['C']
listoflists = [l1,l2,l3,l4,l5,l6]

f = open("out.txt","w")

# for each list and
# for each item in the list;
# write the item to the file, separated by a comma
for list in listoflists: 
    for item in list: 
        f.write(item+",") 

f.close()

Out.txt 现在包含:

1,A,2,B,3,C,

哦,如果没有单行解决方案,任何 Python 问题都是不完整的(这也删除了我最初响应中的尾随逗号)。

open("out.txt","w").write(",".join(("".join(i) for i in listoflists)))

Out.txt 现在包含:

1,A,2,B,3,C

I think the best way to solve this is just with a basic nested loop. Try this:

l1 = ['1']
l2 = ['A']
l3 = ['2']
l4 = ['B']
l5 = ['3']
l6 = ['C']
listoflists = [l1,l2,l3,l4,l5,l6]

f = open("out.txt","w")

# for each list and
# for each item in the list;
# write the item to the file, separated by a comma
for list in listoflists: 
    for item in list: 
        f.write(item+",") 

f.close()

Out.txt now holds:

1,A,2,B,3,C,

Oh, and no Python question is complete without a one-liner solution (this also removes the trailing comma from my initial response).

open("out.txt","w").write(",".join(("".join(i) for i in listoflists)))

Out.txt now holds:

1,A,2,B,3,C
别靠近我心 2024-08-27 20:13:28

您的代码可以简单得多:

for list in listoflists:
    f.write(str(list))
    f.write('\n')

但是,这将打印类似 ['1'] 的内容。看起来你想要的东西更像是:

for list in listoflists:
    f.write(str(list[0]))
    f.write('\n')

另外,为什么你有一堆单元素列表?不能将所有元素放入一个列表中吗?

Your code could be a lot simpler:

for list in listoflists:
    f.write(str(list))
    f.write('\n')

But, this is going to print something like ['1']. It seems like you want something more like:

for list in listoflists:
    f.write(str(list[0]))
    f.write('\n')

Also, why do you have a bunch of single-element lists? Couldn't you put all the elements into one list?

别挽留 2024-08-27 20:13:28

您获得错误文件内容的简单原因是您调用了 iter 两次。第 15-16 行是:

itr.next()
s = str(itr.next())

有关更多 Pythonic 打印语义,请参阅其他答案

The simple reason why you are getting the wrong file contents is because you are calling iter twice. Lines 15-16 are:

itr.next()
s = str(itr.next())

For more Pythonic printing semantics, see the other answers

£冰雨忧蓝° 2024-08-27 20:13:28

在输出中包含引号有点奇怪,但如果您坚持:

for entry in listoflists:
  print >>f, repr(entry[0])

您没有指定如果内部列表不只有一个元素会发生什么,因此这里忽略任何其他可能性。

Including the quotes in the output is a bit odd, but if you insist:

for entry in listoflists:
  print >>f, repr(entry[0])

You don't specify what will happen if the inner list does not have just one element, so any other possibility is ignored here.

海螺姑娘 2024-08-27 20:13:28

您可以简单地使用 itertools.chain 迭代所有列表元素(记录为 此处):

import itertools

l1 = ['1']
l2 = ['A']
l3 = ['2']
l4 = ['B']
l5 = ['3']
l6 = ['C']

chainedlists = itertools.chain(l1,l2,l3,l4,l5,l6)

with open ('order.txt','wt') as f:
    for element in chainedlists:
        # Change this how you want it to be formatted, it will output
        # a string "a" as 'a' (with the quotes)
        f.write("%s\n" % repr(element))

You can simply iterate through all list elements with itertools.chain (documented here):

import itertools

l1 = ['1']
l2 = ['A']
l3 = ['2']
l4 = ['B']
l5 = ['3']
l6 = ['C']

chainedlists = itertools.chain(l1,l2,l3,l4,l5,l6)

with open ('order.txt','wt') as f:
    for element in chainedlists:
        # Change this how you want it to be formatted, it will output
        # a string "a" as 'a' (with the quotes)
        f.write("%s\n" % repr(element))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文