[英]List of tuples to text file
I have a List consists of String and Number like this:我有一个由字符串和数字组成的列表,如下所示:
mylist= [('AGT', 3), ('GTT', 2), ('TTC', 2), ('GTA', 1), ('TAC', 1), ('ACG', 1)]
and want to print to an output file like this并想像这样打印到 output 文件
#output.txt
AGT,3
GTT,2
TTC,2
GTA,1
TAC,1
....
I have tried this code我试过这段代码
with open('output.txt', 'w+') as file:
file.write('\n'.join(map(str, mylist))) #the join function convert the list to string
return kFreq
and here is the output:这是 output:
('AGT', 3)
('GTT', 2)
('TTC', 2)
('GTA', 1)
('TAC', 1)
('ACG', 1)
how do I get rid of the ( and ' ' character?如何摆脱 ( 和 ' ' 字符?
You have to iterate over the tuples and join
them into strings.您必须遍历元组并将它们
join
成字符串。 Also you'll need to cast all items to str
for that:此外,您需要为此将所有项目转换为
str
:
print(*(','.join(map(str,i)) for i in mylist), sep='\n')
AGT,3
GTT,2
TTC,2
GTA,1
TAC,1
ACG,1
If you want it into a file:如果你想把它放到一个文件中:
with open("output.txt", "w") as text_file:
text_file.write('\n'.join([','.join(map(str,i)) for i in mylist]))
For me it looks like task for so-called f-strings .对我来说,它看起来像是所谓的f-strings的任务。 I would do it following way:
我会这样做:
mylist= [('AGT', 3), ('GTT', 2), ('TTC', 2), ('GTA', 1), ('TAC', 1), ('ACG', 1)]
output = '\n'.join(f"{x},{y}" for x,y in mylist)
print(output) # print to stdout for demonstration purposes
Output: Output:
AGT,3
GTT,2
TTC,2
GTA,1
TAC,1
ACG,1
Be warned that this requires Python 3.6
or newer, if you are limited to older version you might use older ways for example .format
:请注意,这需要
Python 3.6
或更高版本,如果您仅限于旧版本,您可能会使用旧方法,例如.format
:
output = '\n'.join("{},{}".format(x,y) for x,y in mylist)
Regardless of your choice, output
is ready to be written to file, that is:无论您选择哪种方式,
output
准备好写入文件,即:
with open('output.txt', 'w+') as file:
file.write(output)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.