iT邦幫忙

0

python 如何str轉換成float 進行運算

我想進行運算 但我要轉成float 要如何比較方便

print(collected_list)

[[('0.017', '0.107'), ('0.018', '0.115'), ('0.019', '0.113'), ('0.02', '0.109')], [('0.067', '0.218'), ('0.068', '0.253'), ('0.069', '0.234'), ('0.07', '0.182')]]

我要把它變成 float 來做運算 請問可以直接從這邊做改變嗎?

collected_list = list(map(float, collected_list))
print(collected_list)
#print(aa)

結果
TypeError: float() argument must be a string or a number, not 'list'

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
一級屠豬士
iT邦新手 2 級 ‧ 2018-08-28 22:58:04
最佳解答
collected_list = [
[('0.017', '0.107'), ('0.018', '0.115'), ('0.019', '0.113'), ('0.02', '0.109')], 
[('0.067', '0.218'), ('0.068', '0.253'), ('0.069', '0.234'), ('0.07', '0.182')]
]


collected_list2 = [ [(float(x), float(y)) for (x,y) in elems] for elems in collected_list]

print(collected_list2)

[[(0.017, 0.107), (0.018, 0.115), (0.019, 0.113), (0.02, 0.109)], [(0.067, 0.218), (0.068, 0.253), (0.069, 0.234), (0.07, 0.182)]]

https://ithelp.ithome.com.tw/upload/images/20180828/20092833PIDzpDeKwQ.png

hoolada iT邦新手 5 級 ‧ 2018-08-29 00:05:19 檢舉

原來兩個可以分開 我運算只要一行就好 我的那方法可以一次解決[]的 但就是很想知道有沒有辦法可以 一次轉兩個但怎麼想都想不到 非常感謝。

我要發表回答

立即登入回答