【问题标题】:Iterate through a list, and convert string “numbers” to integers遍历一个列表,并将字符串“数字”转换为整数
【发布时间】:2019-12-20 15:44:10
【问题描述】:

我正在尝试将列表中的数字从字符串转换为整数,同时保持其他字符串不变。

我已经准备了以下代码,但是我收到一条错误消息,提示“‘int’类型的参数不可迭代”。

为什么这不起作用,或者有什么更好的方法来解决这个问题?

test_list = ['the','dog','ran','down','984','47','the','chicken','4','77']
numSet = '0123456789'


for i in range(0, len(test_list)):
    for j in numSet:
        if j in test_list[i]:
            test_list[i]=int(test_list[i])

print(test_list)

【问题讨论】:

  • new_list = [int(i) if i.isdigit() else i for i in test_list ]?
  • @Chris,不要使用isdigit(),而是使用isdecimal()

标签: python list for-loop


【解决方案1】:
test_list = ['the','dog','ran','down','984','47','the','chicken','4','77']
numSet = '0123456789'


for i in range(0, len(test_list)):
    for j in numSet:
        if j in str(test_list[i]):
            test_list[i]=int(test_list[i])

print(test_list)

使用这个,在列表中的数值被标注为int的

由于字符将被识别为整数,因此首先它将它们转换为字符串,然后检查字符。例如,如果您采用 47 的 c 情况,numset 将尝试检查 47 中的 0(在数值中,顺便说一句,在操作中检查字符串中的值)。所以我想它会为你总结一下情况

【讨论】:

  • 如果你能用这个str(test_list[i])做一点解释就更好了
  • 由于字符会被识别为整数,首先它将它们转换为string,然后检查字符。例如,如果您采用 47 的 c 情况,numset 将尝试检查 47 中的 0(在数值中,顺便说一句,in 操作检查字符串中的值)。所以我想它会为你总结一下情况
  • 请将此添加到您的答案中。
【解决方案2】:
test_list = [int(test_list[i]) if test_list[i].isdecimal() else test_list[i] for i in range(len(test_list))]

上面的代码示例将数字转换为整数,保持字符串不变。

【讨论】:

  • test_list = [int(i) if i.isdecimal() else i for i in test_list]
【解决方案3】:

您应该使用方法str.isdecimal 告诉您字符串是否为数字。所以'12'.isdecimal()True'A12'.isdecimal()False。可能的解决方案:

for i in range(len(test_list)):
    if test_list[i].isdecimal():
        test_list[i] = int(test_list[i])

请注意,如果元素是浮点数,例如'1.234',不会转换。

编辑:根据下面的评论将isdigit 替换为isdecimal

【讨论】:

  • "³".isdigit() 将返回 True。
  • 从来没有意识到这一点,谢谢!现在将编辑我的答案。
【解决方案4】:
test_list = ['the','dog','ran','down','984','47','123.45','chicken','4','77']

test_list_temp=[]
for item in test_list:
    try:
        int(item)
        test_list_temp.append(int(item))
    except Exception as e:
        try:
            float(item)
            test_list_temp.append(float(item))
        except Exception as e:
            test_list_temp.append(item)

然而,这将无法捕捉到像“³”这样的东西

【讨论】:

  • isinstance('4', int) 将返回 False,这不是 OP 所期望的行为
  • if item.isdecimal() int(item) elif item.count(".") == 1 and item.replace(".", "").isdecimal() float(item) else item
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-14
  • 2021-06-18
  • 1970-01-01
  • 2022-11-13
  • 1970-01-01
  • 2015-07-24
  • 1970-01-01
相关资源
最近更新 更多