[英]Confused on how to print numbers only from list and convert them into float
my code:-我的代码:-
mean_distances = [td.text.strip() for td in rows[3].find_all('td') ]
Output:- Output:-
mean_distances: ['Mean distance from the Sun', 'km AU', '57,909,175
0.38709893', '108,208,930 0.72333199', '149,597,890 1.00000011', '227,936,640 1.52366231', '778,412,010 5.20336301', '1,426,725,400
9.53707032', '2,870,972,200 19.19126393', '4,498,252,900 30.06896348']
I want to extract only the numbers in km (ignore the second number expressing the distance in AU) and covert the str data to float value.我只想提取 km 中的数字(忽略表示 AU 中距离的第二个数字)并将 str 数据转换为浮点值。 How can I do it?我该怎么做?
# loop over the items in mean_distances
# skip the first two rows which are the caption and column headers
for item in mean_distances[2:]:
# split this item into km and au
km, au = item.split()
# remove commas from km
km = km.replace(",", "")
# convert km to float
km = float(km)
float_value = [float(item.split()[1]) for item in mean_distances[2:]]
If you know that the items like Mean distance from the Sun
and km AU
will always take up exactly the first two items, you can use the str.split()
method to cut off everything after the first space and the float()
method to convert it to a float:如果您知道诸如Mean distance from the Sun
和km AU
之类的项目将始终占据前两项,您可以使用str.split()
方法将第一个空格之后的所有内容和float()
方法截断将其转换为浮点数:
temp = []
for distance in mean_distances[2:]:
temp.append(float(distance.split(" ")[0].replace(",", "")))
mean_distances = temp
This gives an output of [57909175.0, 108208930.0, 149597890.0, 227936640.0, 778412010.0, 1426725400.0, 2870972200.0, 4498252900.0]
.这给出了[57909175.0, 108208930.0, 149597890.0, 227936640.0, 778412010.0, 1426725400.0, 2870972200.0, 4498252900.0]
。
Try this:尝试这个:
m=[]
for i in range(2,len(l)):
m.append(l[i].split()[0])
res=[float(i.replace(',', '')) for i in m]
>>> print(res)
[57909175.0, 108208930.0, 149597890.0, 227936640.0, 778412010.0, 1426725400.0, 2870972200.0, 4498252900.0]
If you want to keep ',' as thousands separators, to be more readable, see here for some solutions:如果您想保留 ',' 作为千位分隔符,以提高可读性,请参阅此处了解一些解决方案:
How to print number with commas as thousands separators? 如何用逗号打印数字作为千位分隔符?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.