简体   繁体   English

我想在 python 的二维数组中的一个列表之后换行,并带有文件文本

[英]i want new line after one list in 2D Array in python with a file text

this is my code这是我的代码

list = [["UUU","UCU", "UAU", "UGU"],["UUC", " UCC ", "UAC", " UGC"]]
    
    file = open("codons.txt","w") 
    
    for i in list:
        
        for j in i:
         file.write(j)
         file.write(" ")

this is the desired output这是所需的 output

UUU UCU UAU UGU

UUC UCC UAC UGC

You can do this:你可以这样做:

The below code will concatenate all the values in each row, then add \n to it and write to file.下面的代码将连接每行中的所有值,然后将\n添加到其中并写入文件。

my_list=[["UUU","UCU", "UAU", "UGU"],["UUC", " UCC ", "UAC", " UGC"]]

with open("codons.txt", "w") as f_out:
    for line in my_list:
        f_out.write(' '.join(line) + '\n')

Output of this will be: Output 这将是:

UUU UCU UAU UGU
UUC  UCC  UAC  UGC

Note here that I am not removing the leading and trailing spaces.请注意,我不会删除前导和尾随空格。 If you want the leading and trailing spaces to be removed, the join() statement needs to be modified.如果要删除前导和尾随空格,则需要修改 join() 语句。

If you want the leading and trailing spaces to be stripped so the output looks like this:如果您希望去除前导和尾随空格,则 output 如下所示:

UUU UCU UAU UGU
UUC UCC UAC UGC

Then use the below code instead:然后改用下面的代码:

my_list=[["UUU","UCU", "UAU", "UGU"],["UUC", " UCC ", "UAC", " UGC"]]

with open("codons.txt", "w") as f_out:
    for line in my_list:
        f_out.write(' '.join([item.strip() for item in line]) + '\n')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM