【问题标题】:Split() that recognizes the types识别类型的 Split()
【发布时间】:2016-11-22 00:40:43
【问题描述】:

我有这样一句话:

a='Hello I have 4 ducks'

我为此申请了str.split,所以我现在有了

>>> a.split()
['Hello','I','have','4','ducks'].

问题是每个a.split()[i] 都是一个字符串,但我需要程序识别 4 是一个整数。我需要这个来知道第一个整数在哪个位置,所以我这样做:

if(isinstance(a[i], float) or isinstance(a[i], int)):
    punt=k

但每个a[i] 都是一个字符串。

我可以做一些事情让我的程序识别这个列表中的整数吗?

【问题讨论】:

  • 你研究过其他的字符串方法吗? str.isdigit 可能会有所帮助。或者您可以将try 转换为整数并处理'ducks' 之类的故障吗?
  • 那么,有一种方法类似于 split() 但可以识别每个部分的类型? str.isdigit 会这样做吗?谢谢
  • 不,没有。您必须自己实现该功能,但有一些有用的方法可以相对轻松地实现。
  • 为什么这个问题被否决了?对我来说似乎是一个合理的概念......
  • @JeffG 在几分钟内收到了一堆废话的事实表明,这是 OP 应该自己解决的问题。

标签: python types


【解决方案1】:

你没有定义你想要的输出,因此我不确定这是否是你想要的,但它有效:

a='Hello I have 4 ducks'
a=a.split()
ints=[]
strings=[]
for part in a: 
    try: 
        ints.append(int(part))
    except:
        strings.append(part)

ints,strings

给予:

([4], ['Hello', 'I', 'have', 'ducks'])

如果你想有一个类型列表,那么你可以这样修改:

types = []
for part in a:
    try:
        int(part)
        types.append('int')
    except:
        types.append('string')

types    

给出:

类型

['string', 'string', 'string', 'int', 'string']

【讨论】:

    【解决方案2】:
    demo_list = ['Hello','I','have','4','ducks']
    i=0
    for temp in demo_list:
        print temp
        if temp.isdigit():
            print "This is digit"
            print "It is present at location - ", i
        i=i+1
    

    输出: 这是数字。

    它出现在位置 - 3

    【讨论】:

    • 谢谢!这一功能完美!
    • 请注意,使用enumerate 会更简单。
    【解决方案3】:

    您可以定义自己的split() 版本。这里我把它命名为my_split()。

    def my_split(astring):
        return [find_type(x) for x in astring.split()]
    
    
    def find_type(word):
        try:
            word_type = int(word)
        except ValueError:
            try:
                word_type = float(word)
            except ValueError:
                word_type = word
        return word_type
    
    a = 'Hello I have 4 ducks weighing 3.5 kg each'
    
    split_type = [x for x in my_split(a)]
    print(split_type)
    #['Hello', 'I', 'have', 4, 'ducks', 'weighing', 3.5, 'kg', 'each']
    print([type(x) for x in my_split(a)])
    #[<class 'str'>, <class 'str'>, <class 'str'>, <class 'int'>, <class 'str'>, <class 'str'>, <class 'float'>, <class 'str'>, <class 'str'>]
    
    for i, word in enumerate(split_type):
        if type(word) == int:
            print('Integer found at position {:d}'.format(i + 1))
    # Returns: 'Integer found at position 4'
    

    【讨论】:

      【解决方案4】:

      split() 不会这样做,因为它是特定于字符串的。

      但是,您可以对split 的输出进行后处理,以检查其输出的每个元素是否可以转换为整数 per this answer。比如:

      def maybeCoerceInt(s):
          try: 
              return int(s)
          except ValueError:
              return s
      
      tokens = a.split()
      for i in range(len(tokens)):
          tokens[i] = maybeCoerceInt(tokens[i])
      

      哪个产生

      >>> print(tokens)
      ['Hello', 'I', 'have', 4, 'ducks']
      

      【讨论】:

        【解决方案5】:

        你可以使用 isdigit 函数

        a='Hello I have 4 ducks'
        i=0
        for  x in a.split():
          i+=1
          if x.isdigit():
             print "Element:"+x
             print "Position:"+i
        

        【讨论】:

          【解决方案6】:

          可能使用异常是最好的方法。 (见here)。 isdigit 等其他方法不适用于负数。

          def is_number(s):
              try:
                  float(s)
                  return True
              except ValueError:
                  return False
          

          另请注意:

          float('NaN')
          nan
          

          那么你可以使用:

          if is_number(a[i]):
              punt=k
          

          【讨论】:

            【解决方案7】:

            你可以使用eval函数来做,这是我的回答:

            a = 'Hello I have 4 ducks weighing 3 kg each'
            a = a.split()
            print a
            
            for i in a:
                try:
                    if isinstance(eval(i), int):
                        print "the index of {i} is {index}".format(i=i, index=a.index(i))
                except NameError:
                    pass
            
            # the results
            ['Hello', 'I', 'have', '4', 'ducks', 'weighing', '3', 'kg', 'each']
            the index of 4 is 3
            the index of 3 is 6
            

            【讨论】:

              猜你喜欢
              • 2014-02-08
              • 1970-01-01
              • 2017-06-19
              • 2016-10-18
              • 1970-01-01
              • 1970-01-01
              • 2017-05-15
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多