2016-07-19 46 views
-3

我有這樣的一句話:斯普利特()識別的類型

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]是一個字符串。

我可以做些什麼讓我的程序識別這個列表中的整數嗎?

+0

你看過其他的字符串方法嗎? 'str.isdigit'可能會有所幫助。或者你可以'嘗試'轉換爲整數並處理諸如'鴨子'之類的事情? – jonrsharpe

+0

所以,有一個metod像split()那樣工作,但能夠識別每個部分的類型? str.isdigit會這樣做嗎?謝謝 –

+0

不,沒有。你將不得不自己實現這個功能,但有一些有用的方法可以相對簡單地完成它。 – jonrsharpe

回答

0
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

+0

謝謝!這一個功能完美! –

+3

請注意,使用['enumerate'](https://docs.python.org/3/library/functions.html#enumerate)會更簡單。 – jonrsharpe

+0

歡迎GenísAlgansSeguí!!!如果真的有用,請標記爲有用。 –

0

你沒有定義您希望輸出,因此我不知道這是否是你想要的,但它的工作原理:

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

您可以定義自己的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' 
0

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

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

可能使用的例外是最好的方式。 (見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 
0

可以使用eval功能來做到這一點,這是我的anwser:

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