检查Python列表中的项目是否为int/number [英] Check if item in a Python list is an int/number

查看:64
本文介绍了检查Python列表中的项目是否为int/number的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python脚本,该脚本读取.csv文件并将每个值存储到列表列表中:list [x] [y].我对此没有任何问题.

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).

当我执行 print type(list [i] [0])时,即使值是100,它也会返回< type'str'>

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

下面的if语句在 for 循环中循环遍历列表,因此我想做的是进行检查:

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

此方法有效,但是在PEP8中对此并不满意,因此我应该使用 isinstance(),因此我将其修改为

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 

但是我遇到了尝试将字符串转换为int的问题(如果用户输入了字符串).

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

我该如何克服?这似乎是一个简单的问题,但是我是Python的新手,所以我想知道一种简洁有效的处理方式.在将其存储到列表中之前,我应该检查该值是否为int吗?

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?

我正在使用Python2.

I am using Python2.

谢谢

edit:我已经将 isinstance()检查包裹在try异常捕获周围,但是我觉得我不必不必只是为了检查某物是否为int而求助于此?只是好奇是否有更整洁的方法来执行此操作.

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.

如前所述,我已使用 isdigit ,但是得到的结果是负面的.

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

即给定此数据集.list [0] [0] = 123,list [1] [0] = asdasd

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

结果:

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

推荐答案

您可以使用它进行检查-这适用于所有数字(正整数和负整数,浮点数和Nan),仅用于 int 或某些子类,可能存在更好的方法.

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.

这篇关于检查Python列表中的项目是否为int/number的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆