在PYTHON中将列表打印为不带[括号]的txt文件 [英] Print list to txt file without [brackets] in PYTHON

查看:92
本文介绍了在PYTHON中将列表打印为不带[括号]的txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取名称列表,将其按字母顺序排列,然后将其打印到新列表中.这是我的代码:

I am trying to take a list of names, alphabetize them and print them to a new list. Here is my code:

names = []
newnames = []
with open("C:/names.txt", "r") as infile:
    for row in infile.readlines():
       name = row.split()
       names.append(name)
    for x in sorted(names):
       newnames.append(x)
    print newnames
f = open("C:/newnames.txt", "w")
f.write("\n".join(str(x) for x in newnames))
f.close()

我的问题是除括号外,它的打印效果都很好:

my problem is that it prints fine except for the brackets:

['Bradley']

['Harold']

['Jackson']

['Lincoln']

['Mercury']

['Shane']

['Sharon']

['Sherry']

['Xavier']

['Zoolander']

我希望该列表在文本文件中不包含括号或引号

I want that list without the brackets or quotations in the text file

推荐答案

在我看来,您只需要调用列表中的元素即可. name = row.split()行将用括号中的内容分隔行(字符串),在本例中为空.所以

It looks to me like you simply need to call the element of the list. The line name = row.split() will split the row (which is a string) by whatever is in the parenthesis, in this case nothing. So

In [1]: "john".split()
Out[1]: ['john']

如果您的文件只是一个名称列表,例如:约翰哈里

If you file is just a list of name eg: John Harry

然后,您不需要拆分行,但是如果您愿意的话,只需索引第0个元素即可.

Then you don't need to split the row, if you do however wish to then simply indexing the 0th element:

row.split()[0]

将为您提供列表中的内容,而不是列表中的内容.

will give you what is in the list as opposed to the list.

这篇关于在PYTHON中将列表打印为不带[括号]的txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆