简体   繁体   中英

Delete all characters but numbers and -+ in a list, Python 2.7

I have a list like this

[u'-107', u'-103', u'-109', u'-101', u'-110', u'-110', u'-110', u'-110', u'-110', u'-110', u'-105', u'-105', u'-105', u'-115', u'-110', u'-110'

This list was created from parsing html with BeautifulSoup. I want to only have the numbers inside the string and the +- sign, for example: -107 for the first list value. Then I want to create a new list with these values.

Like this:

[-107,-103,-109. . . . . . . .]

Bonus Question:

Why is the u showing up?

Solved Solution:

The following code is what ended up working for me:

odds_matrix_cleaned = [str(x) for x in odds_matrix_dirty]
odds_matrix_cleaned = map(int, odds_matrix_cleaned)

Try the following

>>> input_list=[u'-107', u'-103', u'-109', u'-101', u'-110', u'-110', u'-110', u'-110', u'-110', u'-110', u'-105', u'-105', u'-105', u'-115', u'-110', u'-110']
>>> output = [int(x) for x in input_list]
>>> print output
[-107, -103, -109, -101, -110, -110, -110, -110, -110, -110, -105, -105, -105, -115, -110, -110]

Check below examples :

Converting unicode string into integer and float

>>> a=u'-100'

>>> int(a)
-100

>>> float(a)
-100.0

Converting string with decimal into integer

>>> a=u'-100.0'

>>> int(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '-100.0'

Converting empty string or space into integer

>>> int(u' ')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''
>>>

Converting empty string or space into float

>>> float(u' ')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float:
>>>

It seems your value list has some empty strings. So we need to take care of them.

We can take two approaches here

  1. Ignore the empty string

    OR

  2. Append as it is

Below code using second approach

a = [u'-107', u'-103', u'-109', u'-101', u'-110', u'-110', u'-110', u'-110', u'-110', u'-110', u'-105', u'-105', u'-105', u'-115', u'-110', u'-110' ,u' ']

converted = []
for i in a:
    try:
        #Check second example. So convert into float
        converted.append(float(i))
    except ValueError:
        pass

print converted

Output

 C:\Users\Dinesh Pundkar\Desktop>python b.py
[-107.0, -103.0, -109.0, -101.0, -110.0, -110.0, -110.0, -110.0, -110.0, -110.0, -105.0, -105.0, -105.0, -115.0, -110.0, -110.0]

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