#!/usr/bin/python
b_list = []
for l in range(1,4):
file=open('/Users/sgeorge/file%i.txt' % l, 'r')
m1=[(i.strip()) for i in file]
for j in m1:
b_list.append(filter(None,[(k.strip()) for k in j]))
#print b_list
a = [[0,0,0],[0,0,0],[0,0,0]]
for i in range(0,9,3):
a[0][0] += int(b_list[i][0])
a[0][1] += int(b_list[i][1])
a[0][2] += int(b_list[i][2])
for i in range(1,9,3):
a[1][0] += int(b_list[i][0])
a[1][1] += int(b_list[i][1])
a[1][2] += int(b_list[i][2])
for i in range(2,9,3):
a[2][0] += int(b_list[i][0])
a[2][1] += int(b_list[i][1])
a[2][2] += int(b_list[i][2])
for j in a:
print j[0],j[1],j[2]
输出:
$ python stack.py
9 6 6
4 11 8
12 11 13
上面的脚本只处理三个文件file1.txt
(file2.txt
和file3.txt
)
如果要处理 50 个此类文件,请使用以下命令:
#!/usr/bin/python
b_list = []
for l in range(1,51):
file=open('/Users/sgeorge/file%i.txt' % l, 'r')
m1=[(i.strip()) for i in file]
for j in m1:
b_list.append(filter(None,[(k.strip()) for k in j]))
#print b_list
a = [[0,0,0],[0,0,0],[0,0,0]]
for i in range(0,150,3):
a[0][0] += int(b_list[i][0])
a[0][1] += int(b_list[i][1])
a[0][2] += int(b_list[i][2])
for i in range(1,150,3):
a[1][0] += int(b_list[i][0])
a[1][1] += int(b_list[i][1])
a[1][2] += int(b_list[i][2])
for i in range(2,150,3):
a[2][0] += int(b_list[i][0])
a[2][1] += int(b_list[i][1])
a[2][2] += int(b_list[i][2])
for j in a:
print j[0],j[1],j[2]
更新:
>>> a=1
>>> b=1.1
>>> type(a)
<type 'int'>
>>> type(b)
<type 'float'>
>>> float(a)+float(b)
2.1
>>>
我上面的脚本不会处理float
数字。对于相同的处理,请使用以下命令:
#!/usr/bin/python
b_list = []
for l in range(1,4):
file=open('/Users/sgeorge/file%i.txt' % l, 'r')
m1=[(i.strip()) for i in file]
for j in m1:
b_list.append(j.replace('\n','').split(' '))
#print b_list
a = [[0,0,0],[0,0,0],[0,0,0]]
for i in range(0,9,3):
a[0][0] += float(b_list[i][0])
a[0][1] += float(b_list[i][1])
a[0][2] += float(b_list[i][2])
for i in range(1,9,3):
a[1][0] += float(b_list[i][0])
a[1][1] += float(b_list[i][1])
a[1][2] += float(b_list[i][2])
for i in range(2,9,3):
a[2][0] += float(b_list[i][0])
a[2][1] += float(b_list[i][1])
a[2][2] += float(b_list[i][2])
for j in a:
print j[0],j[1],j[2]
输出:
$ python stack.py
9.0 6.0 6.0
4.0 11.0 8.0
12.0 11.0 13.0