[英]Extract only the integers from list (not the floats)
I have some problems with the following issue: 我遇到以下问题:
I have a string, which contains integers and floats. 我有一个字符串,其中包含整数和浮点数。 I fail to extract only the integers (NOT the floats!).
我无法仅提取整数(不是浮点数!)。
What i have (it is a string): 我有(它是一个字符串):
f= "0:6.0 3:5.6 54:12.3 56:12.0"
How the result should be (not in a string form): 结果应如何(不是字符串形式):
0,3,54,56
I searched on Google (and stack-overflow) which leads to this solution: 我在Google上搜索(并且出现了堆栈溢出),从而得出了以下解决方案:
[int(s) for s in f.split() if s.isdigit()]
That leads to a empty list. 这导致一个空列表。
Other solutions like: 其他解决方案如:
int(re.search(r'\d+', f).group())
Leads to "0 integers". 导致“ 0整数”。 Sorry i'm new but I really can't solve this.
抱歉,我是新手,但我真的无法解决此问题。
You can use .partition(':') : 您可以使用.partition(':') :
>>> s="0:6.0 3:5.6 54:12.3 56:12.0"
>>> [e.partition(':')[0] for e in s.split()]
['0', '3', '54', '56']
Then call int
on those strings: 然后在这些字符串上调用
int
:
>>> [int(e.partition(':')[0]) for e in s.split()]
[0, 3, 54, 56]
Or, 要么,
>>> map(int, (e.partition(':')[0] for e in s.split()))
[0, 3, 54, 56]
And you can use the same method (with a slight change) to get the floats: 您可以使用相同的方法(稍有变化)来获取浮点数:
>>> map(float, (e.partition(':')[2] for e in s.split()))
[6.0, 5.6, 12.3, 12.0]
Fair question asked in comments: Why use partition ? 在评论中问的公平问题: 为什么要使用分区? you can use int(split(":")[0])
您可以使用int(split(“:”)[0])
.partition
it is clear to all readers (including your future self) that you are looking at 1 split only. .partition
,所有读者(包括您将来的自己)都可以清楚地看到,您只看1个拆分。 (Granted, you could use the 2 argument form of split(delimiter, maxsplit)
but I think that is less clear for a single split...) split(delimiter, maxsplit)
的2个参数形式,但我认为对于单个split来说不太清楚...) tuple[1]
. tuple[1]
的真实性即可。 .partion
in tuple assignments of the form lh,delimiter,rh=string.partion('delimiter')
where lh, rh=string.split('delimiter')
will produce a ValueError
if the delimiter is not found. lh,delimiter,rh=string.partion('delimiter')
元组分配中安全地使用.partion
,其中lh, rh=string.split('delimiter')
如果找不到分隔符,则lh, rh=string.split('delimiter')
会产生ValueError
。 ''.join(tuple_from_partion)
vs split
since the delimiter in split
is lost. ''.join(tuple_from_partion)
VS split
由于在分隔符split
丢失。 How about using the following regex: 如何使用以下正则表达式:
import re
f = "0:6.0 3:5.6 54:12.3 56:12.0"
answer = [int(x) for x in re.findall(r'\d{1,2}(?=:)', f)]
print(answer)
Output 产量
[0, 3, 54, 56]
You can also achieve the same result using map
instead of a list comprehension (as in @dawg's answer): 您也可以使用
map
而不是列表理解来实现相同的结果(如@dawg的答案):
answer = map(int, re.findall(r'\d{1,2}(?=:)', f))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.