【问题标题】:how to determine an integer in a string list [duplicate]如何确定字符串列表中的整数[重复]
【发布时间】:2015-01-12 16:21:15
【问题描述】:

如果我有一个字符串列表,我会遇到问题

例如:

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, 单身汉, 13, 未婚, 行政文员, 非家庭成员, 白人, 男性, 2174, 0, 40, 美国,

第二个我需要将这些数据转换成特定的数字 ex State-gov 进入 2:1 Self-emp-not-inc 进入 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')

【问题讨论】:

  • 我不认为这个问题是重复的!!!
  • 我同意 100%,这是一个完全不同的问题。起初我想,“什么,真的有可能 Python 如此蹩脚,以至于数组的所有元素都必须是相同的类型,就像原来的 BASIC 一样??!”这是我可以解释为什么有人会认为询问如何确定数组元素是否为整数的问题与如何检查字符串是否可以用数字表示的问题相同的唯一方法。谢天谢地,it's not。我正在投票重新开放。

标签: python string int converter


【解决方案1】:

函数type,返回对象的类型

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

【讨论】:

  • OP 指定了一个字符串列表。此外,isinstance 通常比 type 更受欢迎。
  • 你能简单解释一下我是python Q的新手
【解决方案2】:
>>> "13".isdigit()
True
>>> 

【讨论】:

    【解决方案3】:

    如果要检查条目的类型,并且列表中有多种元素,则需要使用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']
    

    【讨论】:

    • 但我还需要转换aaa----->例如1:1
    • @jackson 为什么?它不包含任何数字?
    • 我正在尝试进行数据挖掘,我必须将一些信息转换为数字 ex: U.S.A----->10:1
    • 那么基于什么逻辑?你也没有在你的问题 1 中谈到字符串!!!
    • 所以我这样做 if(token[i] in 'State-gov'): result.append("2:1") 如果数据是字符串而不是数字
    猜你喜欢
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 2016-06-13
    • 2011-10-29
    • 2012-05-08
    • 2019-08-27
    相关资源
    最近更新 更多