【问题标题】:how to 2 list of data from textfiles in python如何从python中的文本文件中获取2个数据列表
【发布时间】:2018-03-09 11:16:09
【问题描述】:

我希望将 AAA.txt 的每个元素平方并添加到 bbb.txt 以创建一个大的新数组,字符串/称为 c 的任何内容

def mi_func(P):
    f=open(P, 'r')
    first = f.readline()
    restlines= f.readlines()
    f.close()
    return first, restlines


afirst,arest = mi_func('aaa.txt')
bfirst,brest = mi_func('bbb.txt')



arest = [x.lstrip('0').split(',') for x in arest if x != '\n']     #strip it split it get rid of ends of lines
brest = [x.lstrip('0').split(',') for x in brest if x != '\n']

for i in range(len(arest)):                                             
    arest[i] = [float(x) for x in arest[i] if x != '\n' and x!= '']
print(arest)

for i in range(len(brest)):
    s= brest[i] = [float(x) for x in brest[i] if x != '\n' and x != '']


c = 0
for i in range(len(arest)):
    for j in range(len(arest[i])):
        c += (arest[i][j]**2)+(brest[i][j]**2)
print(c)

我只是想让 c 成为另一个,列表或数组或 w/e

aaa.txt 在下面

test a line 1

3,6,8,99,-4,0.6,8

0,9,7,5,7,9,5

2,2,2,2,2,2,5

7,5,1,2,12,8,0.9

bbb.txt 在下面

test b line 1

1,2,3,4,5,6,7,8

55,0,90,09,1,2,3,

8,9,7,6,8,7,6

3,43,5,8,2,4,1

【问题讨论】:

  • 你之前已经问过这个问题了。
  • 不,我没有这略有不同,我第一次得到的答案从未奏效
  • 首先你需要决定你希望你的输出是什么。一个列表?一个号码?字典?

标签: python string


【解决方案1】:

如果您想迭代多个列表,您可以使用“zip”。例如

for a,b in zip(listA,ListB):
       c = square(a) + b
       listC.append(c);

【讨论】:

  • NameError: name 'square' is not defined 所以我尝试 a,b in zip(arest,brest): c = a2 + b2 listC.append( C); print(listC) 但我得到 ypeError Traceback (最近一次调用最后) in () 24 25 for a,b in zip(arest,brest): ---> 26 c = a**2 + b 27 listC.append(c); 28 print(listC) TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int' so its still not float :'(
  • 这只是一个伪代码,你应该弄清楚如何计算一个数字的平方。您可以按如下方式计算平方:square = value**2
  • 我做到了。我最大的问题是无论我做什么,数据都不会变成浮动的,所以我无法对其进行平方。
  • 您可以根据“,”拆分字符串,然后可以将其类型转换为浮点数。
  • arest = [x.lstrip('0').split(',') for x in arest if x != '\n'] 我已经这样做了吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多