【问题标题】:select number from list of string从字符串列表中选择数字
【发布时间】:2016-10-25 10:52:33
【问题描述】:

我想将字符串列表转换为数字列表,但没有运气

我的字符串是这样的

x=[u'9-9', u'-5-5',u'-45-45',u'99-99']

我想把它转换成:

x=[9,-5,-45,99]

我尝试在列表中循环并在列表中的每个字符串中使用 string.replace('-','') 替换“-”以删除“-”并将数字分成 2 步,但字符串保留有字符“-”替换不工作

我的一些代码:

import string
x=[u'9-9', u'-5-5',u'-45-45',u'99-99']
for i in x:
    string.replace(str(i),"-",' ')
    print i

输出:

9-9
-5-5
-45-45
99-99

有什么帮助吗?

【问题讨论】:

    标签: python string list python-2.7 replace


    【解决方案1】:

    正如所指出的,python 中的字符串是不可变的。对它们的操作返回新字符串而不是更改原始字符串。您的输出要求也是一个整数列表,因此您必须解析字符串:

    In [1]: x=[u'9-9', u'-5-5',u'-45-45',u'99-99']
    
    In [2]: [int(i.rsplit('-', 1)[0]) for i in x]
    Out[2]: [9, -5, -45, 99]
    

    使用list comprehension,字符串是split starting from right 1 次,仅使用'-' 作为分隔符,第一个字符串被拾取并解析为整数。

    【讨论】:

      【解决方案2】:

      使用正则表达式:

      import re
      
      x = [u'9-9', u'-5-5',u'-45-45',u'99-99']
      regex = "([-]?\d*)-.*"
      
      x = [int(re.search(regex, m).group(1)) for m in x]
      print(x)
      # [9, -5, -45, 99]
      

      【讨论】:

        【解决方案3】:

        str.replace 不在位。它返回一个带有替换字符的新字符串。因此:

        for i in x:
            string.replace(str(i),"-",' ')
        

        不影响x 中的字符串。

        您还应该直接在您拥有的字符串对象上调用replace,而不是从string 模块调用通用replace

        相反,你应该做的是:

        x = [u'9-9', u'-5-5',u'-45-45',u'99-99']
        x_int = [int(string.replace('-', '')) for string in x]
        print x_int
        >> [99, 55, 4545, 9999]
        

        还有一小段代码强调str.replace返回一个新字符串:

        x = [u'9-9', u'-5-5',u'-45-45',u'99-99']
        for i in x:
            print i.replace(,"-",'')
            print i
        >> 99
           9-9
           55
           -5-5
           4545
           -45-45
           9999
           99-99
        

        【讨论】:

        • 请添加我如何将数字分成两部分并将第二部分删除为 9 - 5 - 45 - 99
        【解决方案4】:

        id 喜欢使用 e 正则表达式。看看here 并使用this 来编写一个正则表达式

        import re
        
        x=[u'9-9', u'-5-5',u'-45-45',u'99-99']
        rexp = '(.*)-\d+'
        c = re.compile(rexp)
        for i in x:
            print(int(c.search(i).groups()[0]))
        

        【讨论】:

          【解决方案5】:
          import re 
          
          [int(re.sub(r"(-\d+$)", r"", i)) for i in x]
          #[9, -5, -45, 99]
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-10-24
            • 2023-04-04
            • 2023-01-03
            • 1970-01-01
            • 1970-01-01
            • 2013-11-15
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多