Reputation: 11
I have a list like this, named x (which I have already split):
['16','bob','2440', '34']
I want to write a code that checks to see if any of the numbers are negative. The code I tried does not work. This is what I have tried:
for num in x:
if num < 0:
print ("Negative number")
Upvotes: 1
Views: 4333
Reputation: 473873
How about checking for -
sign in the beginning of an item and for the rest of an item to consist of digits? One-liner:
>>> a = ["-1", "aa", "3"]
>>> any(s.startswith('-') and s[1:].isdigit() for s in a)
True
Using any
, because you've said that you want to write a code that checks to see if any of the numbers are negative
.
Note: if there can be negative floats, then just replace s[1:]
with s[1:].replace(".", "")
.
Hope that helps.
Upvotes: 2
Reputation: 32429
Your list contains only strings. So you should cast them to floats (or integers, whatever you need) first:
a = ['"16','bob','2440', '-2', '34"']
for x in a:
try:
if float (x) < 0: print ('negative')
except: continue
EDIT: I changes int
to float
as OP is asking for numbers and not exclusively integers.
Upvotes: 6
Reputation: 49846
First, you need to understand that neither '"16' nor '2440' are numbers - they are strings.
Secondly, you need to figure out what you want to do with '"16' - it doesn't represent a number, but I assume you want it to. You could alter these strings, but you should probably just use an appropriate method of splitting in the first place.
That said, you can do this:
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]
Upvotes: 0
Reputation: 1122172
You need to turn your numbers into integers first; use a predicate function to try to do this:
def negative(string):
try:
return int(string.strip('"')) < 0
except ValueError:
return False
The predicate function here also removes quotes; your input list looks like it was not cleaned up properly and you may want to do so first before testing for negative values.
Then use that to test for negative values:
negative_values = [v for v in a if negative(v)]
or test if there are any negative values:
if any(negative(v) for v in a):
print "No negative values please!"
Upvotes: 3