2013-08-01 94 views
0

整數我有這樣一個名單,名爲x(我已經分手):查找列表

['16','bob','2440', '34'] 

我想寫一個檢查,看看是否有任何數字是負代碼。我試過的代碼不起作用。這是我所嘗試的:

for num in x: 
    if num < 0: 
     print ("Negative number") 

回答

5

您的列表只包含字符串。所以,你應該他們先轉換爲浮動(或整數,無論​​你需要):

a = ['"16','bob','2440', '-2', '34"'] 
for x in a: 
    try: 
     if float (x) < 0: print ('negative') 
    except: continue 

編輯:我改變intfloat作爲OP是要求數字和不完全的整數。

+1

也可能消除虛假報價。或者首先分得更好。 – geoffspear

+3

在那裏我不確定OP的數據來自哪裏。也許''16'是一個有效的元素,但肯定沒有整數 – Hyperboreus

3

您需要先將您的數字轉換爲整數;使用謂詞函數試圖做到這一點:

def negative(string): 
    try: 
     return int(string.strip('"')) < 0 
    except ValueError: 
     return False 

這裏的謂詞函數也刪除引號;您的輸入列表看起來好像沒有正確清理,您可能需要在測試負值之前先執行第一個

然後用它來測試負值:

negative_values = [v for v in a if negative(v)] 

或測試是否有任何負值:

if any(negative(v) for v in a): 
    print "No negative values please!" 
+0

或者使用Martijn的代碼來檢查是否包含一個負數(我認爲OP是在尋找什麼):'any(negative(x)for x在a)' – Hyperboreus

2

怎麼樣在一個項目的開始爲-標誌檢查併爲其餘的項目組成的數字?一內膽:

>>> a = ["-1", "aa", "3"] 
>>> any(s.startswith('-') and s[1:].isdigit() for s in a) 
True 

使用any,因爲你說你want to write a code that checks to see if any of the numbers are negative

注意:如果可能存在負浮動,則只需將s[1:]替換爲s[1:].replace(".", "")即可。

希望有所幫助。

+0

有趣的方法,但取決於OP的輸入數據,這可能會導致不需要的結果,如http:// stackoverflow中記錄的問題。com/questions/10604074/python-isdigit-function-return-true-for-non-digit-character -u-u2466(雖然這也可能是可取的,所以+1)。 – Zigsaz

+0

謝謝你,好點。是的,嘗試'int()'或'float()'可能更安全。 – alecxe

0

首先,你要明白,無論是「'16' 也不是‘2440’是數字 - 他們是字符串

其次,你需要弄清楚你想要做什麼」「16' - 這並不代表一個數字,但我認爲你想要它。你可以改變這些字符串,但你應該首先使用合適的分割方法。

這就是說,你可以這樣做:

x = ['"16','bob','2440', '34"'] 

def int_is_negative(s) 
    try:  
     return int(s) < 0 
    except ValueError: 
     return False 

is_negative_num = [int_is_negative(s) for s in x]