[英]How to convert numbers from file with strings to integer in a list in python
[英]How to read strings from a csv file and convert it into a integer array?
我正在尋找借助 csv 文件中的數據創建 integer 數組的最優化方法。
csv 文件(“sample.csv”)數據如下,
預測1 | 預測2 | 預測3 |
---|---|---|
低的 | 低的 | 低的 |
低的 | 高的 | 高的 |
其中低= 1,高= 3,
我想從 csv 讀取這些數據並制作一個看起來像這樣的數組,
array =
[[1,1,1],
[1,3,3]]
import csv
import sys
num1 = 'low'
num2 = 'high'
csv_file = csv.reader(open('sample.csv', "r"), delimiter=",")
count = 0
for row in csv_file:
if count == 1:
if num1 == row[0]:
dat1 = 1
elif num2 == row[0]:
dat1 = 3
if num1 == row[1]:
dat2 = 1
elif num2 == row[1]:
dat2 = 3
if num1 == row[2]:
dat3 = 1
elif num2 == row[2]:
dat3 = 3
count = count + 1
array =[dat1,dat2,dat3]
這種方法有效,但似乎效率低下。 尋找一種替代和優化的方法來實現這一目標。
使用dict
進行查找和列表理解
前任:
check = {'low': 1, "high": 3}
with open('sample.csv') as infile:
csv_file = csv.reader(infile)
next(csv_file) # skip header
result = [[check[c] for c in row] for row in csv_file]
由於 CSV 文件非常簡單,您甚至可以在沒有 CSV package 的情況下執行此操作:
# We open the CSV file
with open('sample.csv') as file:
# We read all the lines and store them in a list
lines = file.readlines()
# We remove the CSV header
lines = lines[1:]
# We create the array
array = [
[{
'low': 1,
'high': 3
}.get(value.strip()) for value in line.split(',')
] for line in lines]
# We print the array
print(array)
這將打印以下數組: [[1, 1, 1], [1, 3, 3]]
請注意使用dict
的get
方法來避免錯誤,以防 CSV 有不需要的值。 在這些情況下,數組將包含None
值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.