简体   繁体   English

将字符串列表中的数字转换为 Python 中的 int

[英]Converting numbers in a String list to a int in Python

How do I convert this list... list = ['1', 'hello', 'bob', '2', 'third', '3', '0']如何转换此列表... list = ['1', 'hello', 'bob', '2', 'third', '3', '0']

To this list.. list = [1, 'hello', 'bob', 2, 'third', 3, 'N/A']到这个列表.. list = [1, 'hello', 'bob', 2, 'third', 3, 'N/A']

or或者

list = [1, 2, 3, 'N/A']列表 = [1, 2, 3, 'N/A']

Basically I am scrapping data to a list and I need the number from that list & I need to convert all Zero's into N/A.基本上我正在将数据报废到一个列表中,我需要该列表中的数字并且我需要将所有零转换为 N/A。 I have tried looping thru the list and replacing it and I get different type errors.我尝试遍历列表并替换它,但我得到了不同的类型错误。

for i in list:
    if int(list[i]) == 0:
        call_list[i] = 'N/A'

TypeError: list indices must be integers or slices, not str TypeError:列表索引必须是整数或切片,而不是 str

If anyone could help, that would be awesome.如果有人可以提供帮助,那就太棒了。 Thanks谢谢

I suspect your main issue here is that you don't know that str.isdigit() exists, which tests whether a string represents a number (ie you can convert it to a number without hitting a ValueError .我怀疑您的主要问题是您不知道str.isdigit()存在,它测试字符串是否代表数字(即您可以将其转换为数字而不会遇到ValueError

Also, if you want to iterate over the indices in a list, you have to do for i in range(len(your_list)) , instead of for element in your_list .此外,如果您想遍历列表中的索引,则必须执行for i in range(len(your_list)) ,而不是for element in your_list Python uses for-each loops, unlike languages like C, and the built-in function range() will just produce a list of numbers from 0 to whatever its argument is (in this case, len(your_list) ) which you can iterate over and use as indices. Python uses for-each loops, unlike languages like C, and the built-in function range() will just produce a list of numbers from 0 to whatever its argument is (in this case, len(your_list) ) which you can iterate over并用作索引。

lst = ['1', 'hello', 'bob', '2', 'third', '3', '0']

for i in range(len(lst)):
    if lst[i].isdigit():
        lst[i] = int(lst[i])
        if lst[i] == 0:
            lst[i] = 'N/A'

print(lst)

An easy approach is to define a function that says what you want to do with each item:一个简单的方法是定义一个 function 来说明你想对每个项目做什么:

def convert(item):
    try:
        return int(item) or 'N/A'
    except ValueError:
        return None  # or the original item?

and then use the function to build your new list:然后使用 function 构建您的新列表:

>>> data = ['1', 'hello', 'bob', '2', 'third', '3', '0']
>>> [convert(d) for d in data if convert(d) is not None]
[1, 2, 3, 'N/A']

Note that if you change the last line of the function to return item , you can keep the original versions of the items that don't convert into ints:请注意,如果您将 function 的最后一行更改为return item ,您可以保留未转换为 int 的项目的原始版本:

>>> def convert(item):
...     try:
...         return int(item) or 'N/A'
...     except ValueError:
...         return item
...
>>> [convert(d) for d in data]
[1, 'hello', 'bob', 2, 'third', 3, 'N/A']

You need a custom conversion function which can deal with you specific requirements and then use it for list comprehension.您需要一个自定义转换 function 可以处理您的特定要求,然后将其用于列表理解。

mylist = ['1', 'hello', 'bob', '2', 'third', '3', '0']

def convert(text: str):
  try:
      i = int(text)
  except (TypeError, ValueError):
      return text
  return "N/A" if i==0 else i

new_list = [convert(x) for x in mylist]
new_list2 = [x for x in new_list if isinstance(x, int) or x=='N/A']

using a list comprehension that checks if an item is a digit but not a zero if it is, it converts it to int, otherwise it checks if it is zero and converts it to 'N/A' and finaly keeps everything else intact使用列表推导来检查项目是否为数字但如果是则不是零,它将其转换为 int,否则它检查它是否为零并将其转换为“N/A”并最终保持其他所有内容不变

l =['1', 'hello', 'bob', '2', 'third', '3', '0']
print ([int(item) if item.isdigit() and item != '0' else 'N/A' if item == '0' else item for item in l])

outputs: [1, 'hello', 'bob', 2, 'third', 3, 'N/A']输出: [1, 'hello', 'bob', 2, 'third', 3, 'N/A']

or the same in a bit more readable form或以更具可读性的形式相同

print ([
        int(item) if item.isdigit() and item != '0' 
        else 'N/A' if item == '0' 
        else item 
        for item in l
])

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

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