Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 识别类型的Split()_Python_Types - Fatal编程技术网

Python 识别类型的Split()

Python 识别类型的Split(),python,types,Python,Types,我有这样一句话: a='Hello I have 4 ducks' types = [] for part in a: try: int(part) types.append('int') except: types.append('string') types 我将str.split应用于此,因此我现在 >>> a.split() ['Hello','I','have','4','ducks'].

我有这样一句话:

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

types    
我将
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]
都是一个字符串


我能做些什么让我的程序识别这个列表中的整数吗?

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

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'])
如果希望有一个类型列表,则可以按如下方式进行修改:

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

types    
其中:

类型

输出: 这是数字


它位于位置-3

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

def my_分割(astring):
return[在astring.split()中为x查找_类型(x)]
def查找类型(word):
尝试:
单词类型=int(单词)
除值错误外:
尝试:
字类型=浮动(字)
除值错误外:
单词类型=单词
返回字类型
a='你好,我有4只鸭子,每只重3.5公斤'
拆分类型=[x代表我的拆分中的x(a)]
打印(分体式)
#[‘你好’、‘我’、‘有’、‘4只’、‘鸭子’、‘体重’、‘3.5’、‘公斤’、‘每只’]
打印([在我的分割(a)中为x键入(x)])
#[, , , , ]
对于i,枚举中的单词(拆分类型):
如果类型(字)==int:
打印({:d}处的整数)。格式(i+1))
#返回:“在位置4处找到整数”
split()
无法执行此操作,因为它特定于字符串

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

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

您可以使用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

也许使用异常是最好的方法。(见附件)。其他方法,如
isdigit
不适用于负数

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False
另请注意:

float('NaN')
nan
然后你可以使用:

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

您可以使用
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

您研究过其他字符串方法吗
str.isdigit
可能会有所帮助。或者您可以
尝试
到整数的转换,并在
'ducks'
之类的事情上处理失败吗?因此,有一种方法的作用类似于split(),但可以识别每个部分的类型?str.isdigit会这样做吗?谢谢不,没有。你必须自己实现这个功能,但是有一些有用的方法可以相对容易地实现。为什么这个问题会被否决?对我来说似乎是一个合理的概念…@JeffG几分钟内就收到了一连串的垃圾答案,这一事实表明这是OP自己应该做的事情。谢谢!这一个功能完美!请注意,这将更简单。
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