如何确定字符串列表中的整数

时间:2014-11-15 08:50:31

标签: python string int converter

如果我有一个字符串列表

,我有一个问题

例如:

token=[aaa,bbb,ccc,ddd,0,eee,40,ggg,5]

如何检查token[i]是否为整数

我想看看token[i]是否为整数

我将把它放到i+1:number

的新字符串列表中

如果token[4]=0我将把它放入result[5]="5:0"


抱歉解释不清楚 首先,如果我有很多数据 前 39,State-gov,77516,Bachelors,13,N​​ever-married,Adm-clerical,Not-in-family,White,Male,2174,0,40,United States,< = 50K 50,Self-emp-not-inc,83311,Bachelors,13,已婚 - 公民 - 配偶,执行 - 管理,丈夫,白人,男,0,0,13,美国,< = 50K

第二,我需要将这些数据转换为特定的数字 ex State-gov into 2:1 Self-emp-not-inc in 2:2

但是我可以将字符串转换为数字,但我无法将数字转换为数字 如果token[4]=0我将把它放入result[5]="5:0"

for line in lines:
    token=re.split(', ',line)

  for i in range(0,13,1):
    try:
        value = int(token[i])

    except ValueError:
        pass  
    if (token[14] in '<=50K.'):
        result.append('1')
    if (token[14] in '>50K.'):
        result[j].append('2')
    if (value == true):
        result.append('i+1:token[i]')
    if (token[i] in '?'):
        result.append('i+1:0')
    if(token[i] in 'State-gov'):
        result.append("2:1")
    if(token[i] in 'Self-emp-not-inc'):
        result.append('2:2')

3 个答案:

答案 0 :(得分:0)

函数type,返回对象的类型

>>> type(10)
<type 'int'>
>>> type("10")
<type 'str'>

答案 1 :(得分:0)

>>> "13".isdigit()
True
>>> 

答案 2 :(得分:0)

如果要检查条目类型,并且列表中有多个元素,则需要使用isinstance

>>> token=['aaa','bbb','ccc','ddd',0,'eee',40,'ggg',5]
>>> ["{}:{}".format(i,j) for i,j in enumerate(token,1) if isinstance(j,int)]
['5:0', '7:40', '9:5']
相关问题