Check if item in a Python list is an int/number

亡梦爱人 提交于 2020-12-27 06:57:33

问题


I have a Python script that reads in a .csv file and stores each of the values into a list of lists: list[x][y]. I don't have any issues with this.

list = []
i = 0

for row in reader:
     list.append([])
     list[i].append(row[0])
     ...
     i += 1

I want to check one of these fields to see if it's an number (integer).

When I perform a print type(list[i][0]) it returns a <type 'str'> even though the value is say 100.

The if statements below are in a for loop iterating through the lists so what I was thinking of doing is doing a check:

if type(list[i][0] == types.IntType):
     True
else: 
     False

This works, however that's frowned upon in PEP8 and so I should be using isinstance(), therefore I have modified it to

# check if a value is entered
if list[i][0] != '':
    if isinstance(int(list[i][0]), int):
        True
    else: 
        False
else
    False 

But I run into the problem of trying to convert a string to an int (if the user enters a string).

How do I overcome this? It seems like a simple issue however I am new to Python so I was wondering of a neat and efficient way of dealing with this. Should I be checking if the value is an int before storing it into the list?

I am using Python2.

Thanks

edit: I have wrapped the isinstance() check around a try exception catch however I feel like I shouldn't have to resort to this just to check if something is an int or not? Just curious if there was a neater way to do this.

edit: I have used isdigit as mentioned previously however I was getting negative results.

i.e. given this data set. list[0][0] = 123, list[1][0] = asdasd

for i in range(0, 1):
   if (list[i][0]).isdigit:
       tempInt = list[i][0]
       print type(tempInt)
       print 'True: ' + tempInt
   else: 
       tempInt = 1
       print 'False: ' + tempInt

Results:

<type 'str'>
True: 123
<type 'str'>
True: asdasd

回答1:


You can check it with this - this is for all numbers (positive and negative integer, floats, Nan), for only int or certain subclass, better approaches might exist.

def is_number(a):
    # will be True also for 'NaN'
    try:
        number = float(a)
        return True
    except ValueError:
        return False

At face-value, it does not look good. But I think this is probably the best way if you want to consider all number (negative, float, integer, infinity etc), you can see a highly view/voted question/answer here. Also note that isdigit does not work in all cases.




回答2:


The following approach will return for integers only:

string_list = ['20.0', '100', 'abc', '10.3445', 'adsfasdf.adsfasdf', '10,3445', '34,0']

def check(inp):
    try:
        inp = inp.replace(',', '.')
        num_float = float(inp)
        num_int = int(num_float)
        return num_int == num_float
    except ValueError:
        return False

print([check(s) for s in string_list])

Giving:

[True, True, False, False, False, False, True]

The trick is to cast the string to a float first and convert that into an integer (which will round the float if decimal part is not zero). After that you can compare the integer- and float-representation of the input in order to find out if the input was an integer or not. I added .replace() in order to support both european and american/english decimal notation using commas.



来源:https://stackoverflow.com/questions/38496967/check-if-item-in-a-python-list-is-an-int-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!