删除所有字符但数字和 - +列表中的+,Python 2.7

时间:2017-10-24 04:20:30

标签: python html regex list beautifulsoup

我有一个像这样的列表

[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'

此列表是使用BeautifulSoup解析html创建的。我想只在字符串中包含数字和+ - 符号,例如:-107表示第一个列表值。然后我想创建一个包含这些值的新列表。

像这样:

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

奖金问题:

为什么你出现了?

解决方案:

以下代码最终为我工作:

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

2 个答案:

答案 0 :(得分:0)

尝试以下

>>> 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]

答案 1 :(得分:0)

检查以下示例:

将unicode字符串转换为整数并浮动

>>> 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'

将带小数的字符串转换为整数

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

将空字符串或空格转换为整数

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

将空字符串或空格转换为浮动

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

您的值列表似乎有一些空字符串。 所以我们需要照顾它们。

我们可以采取两种方法

  1. 忽略空字符串

  2. 按原样附加

  3. 代码下方使用第二种方法

     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]
    

    <强>输出

    CREATE ALGORITHM=UNDEFINED DEFINER=`acc_webdev`@`%` SQL SECURITY DEFINER VIEW `view_dash_total` AS 
    SELECT
      COUNT(0) AS `jumlah`,
      SYSDATE() AS `tanggal`
    FROM `table_laporan`
    WHERE (STR_TO_DATE(`table_laporan`.`dt_added`,'%d-%m-%Y') < (SYSDATE() + INTERVAL - (1)DAY))$$