简体   繁体   中英

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:

[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". Sorry i'm new but I really can't solve this.

You can use .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(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])

  1. With .partition it is clear to all readers (including your future self) that you are looking at 1 split only. (Granted, you could use the 2 argument form of split(delimiter, maxsplit) but I think that is less clear for a single split...)
  2. It is easier to test successful partitioning since partition always produces a three element tuple and you only need to test the truthiness of the element tuple[1] .
  3. You can safely use .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.
  4. With the delimiter included in the resulting tuple, it is easier to reassemble the original string with ''.join(tuple_from_partion) vs split since the delimiter in split is lost.
  5. Why not?

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):

answer = map(int, re.findall(r'\d{1,2}(?=:)', f))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM