简体   繁体   English

遍历列表,并将字符串“数字”转换为整数

[英]Iterate through a list, and convert string “numbers” to integers

I am trying to convert the numbers in the list from strings to integers, while leaving other strings unchanged. 我正在尝试将列表中的数字从字符串转换为整数,同时保持其他字符串不变。

I have prepared the following code, however I am receiving an error saying, “argument of type 'int' is not iterable”. 我已经准备了以下代码,但是我收到一条错误消息:“'int'类型的参数不可迭代”。

Why is this not working, or what would be a better way of going about this? 为什么这不起作用,或者有什么更好的方法呢?

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

Use this, in the list the numeric values are noted as int's 使用此功能,在列表中将数值标记为int

As the characters would be recognized as integers, first it would convert them to string and then it would be checked for the character. 由于字符将被识别为整数,因此首先会将其转换为字符串,然后再检查字符。 For an example if you take thec case of 47, numset would try to check for 0 in 47 (In numeric values, btw in operation checks for values within a string). 例如,如果您以47为例,numset将尝试检查47中的0(在数字值中,操作中btw将检查字符串中的值)。 So I guess it would sum up the case for you 所以我想这将为您总结情况

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

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

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)

This would however fail to catch something like "³" 但是,这将无法捕获类似“³”的内容

You should use the method str.isdecimal which tells you if a string is a digit. 您应该使用str.isdecimal方法,该方法告诉您字符串是否为数字。 So '12'.isdecimal() is True but 'A12'.isdecimal() is False . 因此'12'.isdecimal()True'A12'.isdecimal()False Possible solution: 可能的解决方案:

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

Note that if an element is a float, eg '1.234' , it will not be converted. 注意,如果一个元素是一个浮点数,例如'1.234' ,它将不会被转换。

Edit: Replaced isdigit with isdecimal as per a comment below. 编辑:按照下面的注释,用isdecimal替换isdigit

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM