[英]Having trouble converting a list of strings into numbers
所以我在這里得到了一個清單:
list1 = ["yo dog", "2", "it's ya boi", "jake", "69.420"]
我希望它的輸出是這樣的,這樣我列表中的所有數字現在都是“浮點數”,但仍然是字符串形式:
["yo dog", "2.0", "it's ya boi", "jake", "69.420"]
這是我嘗試過的:
list1 = [float(x) for x in list1 if is_number(x)]
list1 = [str(x) for x in list1]
基本上它給我留下了:
["2.0", "69.420"] 並刪除所有不是數字的內容。 這很明顯,因為我讓我的舊列表僅等於其中包含數字的字符串。
(is_number() btw 是我用來檢查字符串是否包含數字的函數)
所以很明顯我可以做一個 for 循環並再次添加東西,但我想知道是否有更好的方法來做到這一點。
你可以使用正則表達式:
import re
list1 = ["yo dog", "2", "it's ya boi", "jake", "69.420"]
[str(float(e)) if re.match(r'^-?\d+(?:\.\d+)?$', e) else e for e in list1 ]
輸出:
['yo dog', '2.0', "it's ya boi", 'jake', '69.42']
list1 = ["yo dog", "2", "it's ya boi", "jake", "69.420"]
float_list = []
for string in list1:
try:
float_list.append(str(float(string)))
except ValueError:
#float_list.append(string) # if you want to keep string
pass # if you don't want the string
print(float_list)
您可以使用 try/except 語句嘗試轉換,並在失敗時返回原始字符串:
def floater(s):
try: return str(float(s))
except: return s
list1 = ["yo dog", "-2", "it's ya boi", "jake", "69.420"]
result = list(map(floater,list1))
print(result)
['yo dog', '-2.0', "it's ya boi", 'jake', '69.42']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.