[英]How do I iterate over a list of strings and identify ints and floats and then add them to a list?
I am trying to iterate over list of strings to add both floats and ints to another list.我正在尝试遍历字符串列表以将浮点数和整数添加到另一个列表中。 My code below works for ints, but not for floats and I don't know why.
我下面的代码适用于整数,但不适用于浮点数,我不知道为什么。
My pseudo code would be: for element in list, if element is float or int, add to list.我的伪代码是:对于列表中的元素,如果元素是浮点数或整数,则添加到列表中。
So in the code below I use these two inputs, but you will see the issues.所以在下面的代码中我使用了这两个输入,但你会看到问题。 How can I fix this?
我怎样才能解决这个问题?
theInput1 = "3.2+.4*5.67/6.145="
theInput2 = "11.897/3.4+9.2-0.4*6.9/12.6-16.7="
And here is my code below when I use the first input:下面是我使用第一个输入时的代码:
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)
This is the output that I get:这是我得到的 output:
['3.2', '5.67', '6.145']
I'm not sure what happened to the 0.4?不知道0.4怎么了?
The result for the second input:第二个输入的结果:
['11.897', '3.4', '0.4', '6.9', '12.6', '16.7']
Again the 9.2 is missing...再次缺少 9.2...
For this input without floats it works fine:对于这个没有浮点数的输入,它工作正常:
"(12+3)*(56/2)/(34-4)="
I get this output which works:我得到这个 output 有效:
['12', '3', '56', '2', '34', '4']
Another option is to use re.findall instead of split:另一种选择是使用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: 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])
The individual lists can be accessed like so:可以像这样访问各个列表:
f, i = get_numbers("(12+.3)*(56.36/2.15)/(34-4)=")
The problem is in comparison i <= "9"
.问题在于比较
i <= "9"
。 Obviously "9.2"
fails the check so it isn't added to the list.显然
"9.2"
未通过检查,因此未将其添加到列表中。
You can try:你可以试试:
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)
Prints:印刷:
[11.897, 3.4, 9.2, 0.4, 6.9, 12.6, 16.7]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.