为什么我的输出文件中有括号?

2024-04-26 23:16:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码

with open('base.txt') as infile:
    r = [map(float, line.split()) for line in infile]

r1=r[::3]
r2=tuple(r1)   

with open('newindex1.txt') as infile:
    i = [map(int, line.split()) for line in infile]

a2 = zip(*i)
a11 = a2[0]
a12 = a2[1]    

with open('in.txt','w') as file:
    for index in range(len(r2)):
            file.write(str(a11[index]) + " " + str(a12[index])+ " " + str(r2[index]) + "\n") 

只有几行输出,in.txt

0 0 [1.2]
1 0 [1.2]
2 0 [1.2]
3 0 [1.2]
4 0 [1.2]
5 0 [1.2]
6 0 [1.2]
7 0 [1.2]
8 0 [1.2]
9 0 [1.2]

newindex1.txt

0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0

base.txt

1.200000e+00
1.200000e+00
1.200000e+00
1.200000e+00
1.200000e+00
1.200000e+00
1.200000e+00
1.200000e+00
1.200000e+00
1.200000e+00

我已将列表转换为元组。为什么我有括号?如何摆脱他们?你知道吗


Tags: intxta2mapforbaseindexas
2条回答

列表的每个索引r都是一个list。因此,当您将r2设置为r中的任何值时:

r1=r[::3]
r2=tuple(r1)

您正在将r2设置为具有列表值的元组。str()的列表将打印带括号的内容。你知道吗

之所以使用方括号,是因为您正在将一个列表(显然是一个单元素列表)转换为一个带有str(r2[index])的字符串。 解决此问题的最简单方法是提取唯一元素:将其更改为str(r2[index][0])。你知道吗

我还建议您用字符串模板替换过于生硬的str操作符(顺便说一下,它允许您control the format浮动,例如%.2f),从而降低代码的错误倾向(并提高可读性)

with open('in.txt','w') as file:
    for index in range(len(r2)):
        line = "%d %d %f\n" % (a11[index], a12[index], r2[index][0])
        file.write(line)

如果您是这样做的,并且不小心忘记了[0],您会得到一个(相当有用的)错误:

TypeError: a float is required

您也可以简化您的输入并将base.txt读取为一个简单的浮点列表;但是由于您似乎读取了大量的数字矩阵,因此我将坚持您的通用方法。(说到这里,你应该去看看numpy。二维numpy数组正是这样的东西所需要的。)

相关问题 更多 >