4 回答

TA貢獻1875條經驗 獲得超5個贊
“line.split(',')”用“,”分割字符串并返回列表。對于字符串 '1,8.3,70,10.3' 它將返回 [1, 8.3, 70, 10.3]

TA貢獻1826條經驗 獲得超6個贊
你可以說:
res = line.split(" ")
# map takes a function as the first arg and a list as the second
list_of_floats = list(map(lambda n: float(n), res.split(",")))
# then you can
List_one.append(list_of_floats)
這仍然會給你一個嵌套列表,因為你在每次迭代期間推送一個列表for line in f:,但每個列表至少會是你指定的浮點數。
如果您只想獲得一個平面浮點列表而不是執行初始操作,line.split(' ')您可以使用正則表達式來分割從 csv 讀取的行:
import re # at the top of your file
res = re.split(r'[\s\,]', line)
list_of_floats = list(map(lambda n: float(n), res))
List_one.append(list_of_floats)

TA貢獻1859條經驗 獲得超6個贊
如果需要,您可以用逗號分隔字符串。不過,在將它們附加到 List_one 之前,您可能應該完成所有操作。
res = [float(x) for x in line.split(" ")[0].split(",")] List_one.append(res)
這是否如您所愿?抱歉,我不確定輸入的格式是什么,所以我有點猜測

TA貢獻1827條經驗 獲得超9個贊
這可能有幫助:
l =[['1,8.3,70,10.3'], ['2,8.6,65,10.3'], ['3,8.8,63,10.2'], ['4,10.5,72,16.4']]
l2 =[]
for x in l:
a =x[0].split(",")
l2.append(a)
print(l2)
享受!
- 4 回答
- 0 關注
- 211 瀏覽
添加回答
舉報