![](/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.