[英]How to do math on a read column in Python?
我在將數字添加到列時遇到問題。 例如,如果我有一個給出輸出的代碼:
['1', '2', '3', '7']
['4', '5', '6', '8']
['9', '6', '3', '9']
我想在第一列中添加三個,使其變為4,7,12。 我想在第二列做類似的數學運算。 到目前為止,我只能使用line.split
在第一列中進行line.split
。
with open("data.txt","r") as inData:
for line in inData:
line=line.strip()
x,y,z=line.split("\t",2)
print(x)
這是我到目前為止的代碼。 它打印第一列。
首先,您閱讀文字
In [1]: with open('data.txt', 'r') as df:
txt = df.read()
...:
In [2]: txt
Out[2]: '1 7 12\n2 8 13\n3 9 14\n'
然后將其分解並轉換為數字。
In [3]: items = txt.split()
In [4]: items
Out[4]: ['1', '7', '12', '2', '8', '13', '3', '9', '14']
In [8]: items = [float(n) for n in items]
In [9]: items
Out[9]: [1.0, 7.0, 12.0, 2.0, 8.0, 13.0, 3.0, 9.0, 14.0]
使用切片,您現在可以獲取各個列:
In [10]: items[0::3]
Out[10]: [1.0, 2.0, 3.0]
然后,您可以使用列表理解功能向其添加數字:
In [13]: new1 = [j+3 for j in items[0::3]]
In [14]: new1
Out[14]: [4.0, 5.0, 6.0]
In [15]: new2 = [j-3 for j in items[1::3]]
In [16]: new3 = [j*2 for j in items[2::3]]
In [21]: new2
Out[21]: [4.0, 5.0, 6.0]
In [22]: new3
Out[22]: [24.0, 26.0, 28.0]
然后,您可以將新的列轉換為行。
In [23]: zip(new1, new2, new3)
Out[23]: [(4.0, 4.0, 24.0), (5.0, 5.0, 26.0), (6.0, 6.0, 28.0)]
您可以寫入文件的行。
似乎您想要在文件中包含某種表。 在python中處理表格的一種方法是通過創建列表列表:
table = []
table
將成為我們的桌子。 它被聲明為空列表。
現在,我們需要讀取您的文件。 假設它被稱為“ input.txt”:
f = open('file.txt', 'r')
for line in f:
# Now we can use your command
x, y, z = line.split('\t', 2)
table.append([x, y, z])
此后,您在table[i]
,因為我從0到文件中的行數,其中包含每一行。 table[i][j]
是第i行中的第j個元素,在您的情況下,j從0到2。
現在,您可以使用以下命令向表中的每個數字添加3:
for i in range(0,len(table)):
for j in range(0,3):
table[i][j] = table[i][j] + 3
#This should print each line.
with open("data.txt","r") as inData:
for line in inData:
line=line.strip()
line_list = line.split("\t",2)
print(line_list)
# now add 3 to each and print again
for n in line_list:
new_n = float(n) + 3
print new_n,
print
如果我了解你的權利。 您的data.txt文件包含以下內容:
1 2 3 2 4 6 3 6 9
2 4 6 4 8 12 6 12 18
3 6 9 6 12 18 9 18 27
而你想要得到這樣的東西:
4 5 6 5 7 9 6 9 12
5 7 9 7 11 15 9 15 21
6 9 12 9 15 21 12 21 30
我創建了幾乎可以解決它的東西,然后發現Roland Smith解決方案非常有用,實際上他完美地回答了這個問題(除了寫作),恕我直言。 所以我用他的風格,做到了:
def do_math():
with open("data.txt", "r") as df:
txt = df.read()
items = txt.split()
items = [int(n) for n in items]
data = zip([i+3 for i in items[::3]],
[i+3 for i in items[1::3]],
[i+3 for i in items[2::3]])
with open("data_new.txt", "w") as df:
for i in range(len(data)):
for j in range(len(data[i])):
df.write(str(data[i][j]))
if j < 2:
df.write(" ")
df.write("\t")
# new line
if (i+1)%3==0:
df.write("\n")
希望它有用,即使它不是完美的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.