代码之家  ›  专栏  ›  技术社区  ›  Steve

使用单行筛选字符串python中的数字

  •  0
  • Steve  · 技术社区  · 5 年前

    我正在重构我的代码,以便以一种更为蟒蛇式的方式完成它。具体来说,我有一个部分 这是从字符串返回令牌,如果该令牌不是整数。最初我写的函数如下

     string = "these 5 sentences should not have 2 numbers in them"
     newString = []
     for token in string.split():
         if token.isdigit() == False:
             newString.append(token)
     newString = " ".join(newString)
     print(newString)
    

    虽然这很有效,但我不会让代码看起来不那么笨重。所以我重写如下

       newString = [token for token in string.split() if token is not 
       token.isdigit() ]
    

    4 回复  |  直到 5 年前
        1
  •  2
  •   Adam.Er8    5 年前

    string = "these 5 sentences should not have 2 numbers in them"
    
    newString = " ".join(token for token in string.split() if not token.isdigit())
    
    print(newString)
    

    is

    is is an identity comparison operator

    is not x is y x is not y

    token token.isdigit()

        2
  •  1
  •   Meet Maheshwari    5 年前

    newString = " ".join([x for x in string.split() if x.isdigit() == False])
    

    所有东西只在一行代码中。

        3
  •  1
  •   Piotr Kamoda    5 年前

    在代码中,您正在比较 token token.isdigit() 具有 is not 操作员。如果对象是同一个对象,它会比较这些对象,但是 string boolean 甚至不是同一类型,所以结果总是正确的:

    >>> string = "these 5 sentences should not have 2 numbers in them"
    >>> string.split()
    ['these', '5', 'sentences', 'should', 'not', 'have', '2', 'numbers', 'in', 'them']
    >>> token = string.split()[3]
    >>> token
    'should'
    >>> token.isdigit()
    False
    >>> token is not token.isdigit()
    True
    >>> token = string.split()[1]
    >>> token
    '5'
    >>> token is not token.isdigit()
    True
    

    所以你应该直接下车 token is 从你的代码,应该是好的。

        4
  •  0
  •   Stan S.    5 年前

    比如:

    newstring = ''.join(map(lambda x: x if not x.isdigit() else "", string.split() ))
    

    与空格完全相同:

    newstring = ' '.join(map(lambda x: x if not x.isdigit() else "", string.split() )).replace('  ', ' ')
    
        5
  •  -1
  •   PrakashG user1842676    5 年前

    在我看来,lambda表达式中有一个小错误。
    尝试:

    newString = [token for token in string.split() if not token.isdigit()]
    

    当然 newString 现在是一个列表,但我希望这能回答您最初的问题。