简体   繁体   English

附加值,不带逗号

[英]Append values without commas

I am trying to write a loop that writes a text file with values seperated by spaces only. 我正在尝试编写一个循环,该循环将只用空格分隔的值写入文本文件。 For some reason python is inserting brackets at the beginning and end as well as commas between each value. 出于某种原因,python在开头和结尾以及每个值之间的逗号之间插入了括号。 I have tried join and a couple other methods but have not been succesful. 我尝试了join和其他几种方法,但未成功。

Here is my code: 
import os
import numpy

os.chdir('/Users/DevEnv/Case_1')


try:
    os.remove('fparameters.txt')
except OSError:
    pass

n=50
N=50

tlength=1501  #set number of generations 



for x in range(0,n):
    A=[]
    for i in range(0,tlength):
        Aj=[]
        for v in range(0,N):
            mu_f, sigma_f = 1.5, 0.5  
            Aj.append(60+ numpy.random.lognormal(mu_f, sigma_f, size=None))     

        A.append(Aj)

    outFile = open('fparameters.txt','a')
    for item in A:
        outFile.write('%s ' %item)
    outFile.write('\n')
    outFile.close()

Your help would be greatly appreciated!! 您的帮助将不胜感激!

A is a list of lists of numbers, so item is a list of numbers here: A是数字列表的列表,因此item是这里的数字列表:

for item in A:
    outFile.write('%s ' %item)

To create a string from an iterable of strings, you can use str.join . 要从可迭代的字符串中创建一个字符串,可以使用str.join You have a list of numbers, though, so you'll need to convert each one to a string with str() : 不过,您有一个数字列表,因此需要使用str()将每个数字转换为字符串:

for item in A:
    outFile.write(' '.join(str(x) for x in item))

If the outFile.write('\\n') really isn't indented and you want everything on one line, it might be best to just flatten the list of lists of numbers into one iterable of strings: 如果outFile.write('\\n')确实没有缩进,并且您希望所有内容都在一行上,则最好将数字列表平整为一个可迭代的字符串:

with open('fparameters.txt', 'a') as f:
    print(' '.join(str(x) for item in A for x in item), file=f)

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

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