![](/img/trans.png)
[英]How do I convert a list of strings in a list composed of ints and floats to both ints and floats?
[英]How do I iterate over a list of strings and identify ints and floats and then add them to a list?
我正在嘗試遍歷字符串列表以將浮點數和整數添加到另一個列表中。 我下面的代碼適用於整數,但不適用於浮點數,我不知道為什么。
我的偽代碼是:對於列表中的元素,如果元素是浮點數或整數,則添加到列表中。
所以在下面的代碼中我使用了這兩個輸入,但你會看到問題。 我怎樣才能解決這個問題?
theInput1 = "3.2+.4*5.67/6.145="
theInput2 = "11.897/3.4+9.2-0.4*6.9/12.6-16.7="
下面是我使用第一個輸入時的代碼:
import re
a = "3.2+.4*5.67/6.145="
a2 = [x for x in re.split("(\d*\.?\d*)", a) if x != '']
s = []
for i in a2:
if i >='0' and i <='9':
s.append(i)
print(s)
這是我得到的 output:
['3.2', '5.67', '6.145']
不知道0.4怎么了?
第二個輸入的結果:
['11.897', '3.4', '0.4', '6.9', '12.6', '16.7']
再次缺少 9.2...
對於這個沒有浮點數的輸入,它工作正常:
"(12+3)*(56/2)/(34-4)="
我得到這個 output 有效:
['12', '3', '56', '2', '34', '4']
另一種選擇是使用re.findall而不是 split:
import re
def get_numbers(s):
floats = []
ints = []
for x in re.findall(r"\d*\.?\d+", s):
if '.' in x:
floats.append(float(x))
else:
ints.append(int(x))
return floats, ints
# For Display
print('Floats', get_numbers("11.897/3.4+9.2-0.4*6.9/12.6-16.7=")) # Floats Only
print('Ints ', get_numbers("(12+3)*(56/2)/(34-4)=")) # Ints Only
print('Mixed ', get_numbers("(12+.3)*(56.36/2.15)/(34-4)=")) # Mixed
Output:
Floats ([11.897, 3.4, 9.2, 0.4, 6.9, 12.6, 16.7], [])
Ints ([], [12, 3, 56, 2, 34, 4])
Mixed ([0.3, 56.36, 2.15], [12, 34, 4])
可以像這樣訪問各個列表:
f, i = get_numbers("(12+.3)*(56.36/2.15)/(34-4)=")
問題在於比較i <= "9"
。 顯然"9.2"
未通過檢查,因此未將其添加到列表中。
你可以試試:
import re
a = "11.897/3.4+9.2-0.4*6.9/12.6-16.7="
a2 = [x for x in re.split(r"(\d*\.?\d*)", a) if x != ""]
s = []
for i in a2:
try:
s.append(float(i))
except ValueError:
continue
print(s)
印刷:
[11.897, 3.4, 9.2, 0.4, 6.9, 12.6, 16.7]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.