所以我有一個包含一些資料的 txt 檔案,但它們帶有注釋,我如何輕松地從這里轉到右側只有數字的串列?
1 3.170
2 3.198
3 3.188
4 3.153
5 3.164
6 3.214
7 3.095
8 3.078
9 3.193
10 3.113
我已經通過 3 個步驟完成了
with open('numbers', 'r') as file:
for line in file:
for word in line.split():
print(word)
然后結果
with open('main.py') as f:
lines = f.read().splitlines()
print(lines)
然后我對數字進行排序,然后復制 3 到 4 之間的值
numbers = ('1', '3.170', '2', '3.198', '3', '3.188', '4', '3.153', '5', '3.164', '6', '3.214', '7', '3.095', '8', '3.078', '9', '3.193', '10', '3.113', '11', '3.153', '12', '3.119')
float_lst = [float(item) for item in numbers]
sor = sorted(float_lst)
print(sor)
我怎樣才能讓它作業?
uj5u.com熱心網友回復:
你讓這種方式變得比它需要的更難。
for line in open('numbers'):
print( float(line.rstrip().split()[1]) )
uj5u.com熱心網友回復:
隨手丟棄行號。
with open('numbers', 'r') as file:
numbers = [float(line.rstrip('\n').split()[1]) for line in file]
如果串列理解看起來令人生畏,這里有一個普通版本:
numbers = []
with open('numbers', 'r') as file:
for line in file:
# Trim trailing newline
line = line.rstrip('\n')
# Extract last item
item = line.split()[1]
# Convert to float, add to list
numbers.append(float(item))
作為一般原則,不要隨身攜帶不需要的資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/310973.html
上一篇:Django:覆寫繼承的欄位選項
