[英]Converting elements of list of nested lists from string to integer in python
[英]Converting all the elements of a list from string to integer in Python
我有一個列表,比如list_1
,它看起來像: ['0.93', '1.00', '1.00', '0.93', '0.87']
,現在我想找到該列表所有元素的平均值。 為此,我需要先將所有元素轉換為 integer。 我已經看到了 stackoverflow 的答案並正在嘗試該方法:
print("The list: ",list_1)
total = 0
list_1 = [ int(x) for x in list_1 ]
for ele in range(0, len(list_1)):
total = total + list_1[ele]
final_res=total/no_of_times
這是給出錯誤說: ValueError: invalid literal for int() with base 10: '0.93'
您使用的數字是浮點數而不是整數,因此請改用 float() 。
list = ['0.93', '1.00', '1.00', '0.93', '0.87']
list = [float(i) for i in list]
print(type(list[0]))
output:<類“浮動”>
您無法一步將字符串浮點數轉換為 integer。 如果它們是浮點數而不是字符串,您可以使用int()
但這會四舍五入。
您可以改用float
。
list_1 = ['0.93', '1.00', '1.00', '0.93', '0.87']
print("The list: ",list_1)
total = 0
list_1 = [ float(x) for x in list_1 ]
print(list_1)
output
[0.93, 1.0, 1.0, 0.93, 0.87]
嘗試使用float
而不是int
:
list_1_strs = ['0.93', '1.00', '1.00', '0.93', '0.87']
print(f'{list_1_strs = }')
total = 0
list_1_floats = [float(x) for x in list_1_strs]
print(f'{list_1_floats = }')
for ele in list_1_floats:
total += ele
final_res = total / len(list_1_floats)
print(f'{final_res = :.2f}')
Output:
list_1_strs = ['0.93', '1.00', '1.00', '0.93', '0.87']
list_1_floats = [0.93, 1.0, 1.0, 0.93, 0.87]
final_res = 0.95
請注意,您可以利用sum
和map
計算一行中的平均值:
final_avg = sum(map(float, list_1_strs)) / len(list_1_strs)
這有效:
from decimal import Decimal
lst = ["0.93", "1.00", "1.00", "0.93", "0.87"]
average = sum(map(Decimal, lst)) / len(lst)
print(average)
# output: 0.946
注意:我們可以使用浮點數,但這里我們使用小數來避免典型的浮點數舍入錯誤。
無法執行int('1.93')
轉換浮點值,應該使用float('1.93')
代替
從您的代碼編輯:
list_1 = ['0.93', '1.00', '1.00', '0.93', '0.87']
print("The list: ", list_1)
total = 0
list_1 = [ float(x) for x in list_1 ]
for ele in range(0, len(list_1)):
total = total + list_1[ele]
print('Average is', total/len(list_1))
Output
The list: ['0.93', '1.00', '1.00', '0.93', '0.87']
Average is 0.9460000000000001
與 output 相同的另一個建議:
list_1 = ['0.93', '1.00', '1.00', '0.93', '0.87']
print("The list: ", list_1)
print('Average is', sum([ float(x) for x in list_1 ])/len(list_1))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.