Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何删除python列表中的数字自由字符串并将其转换为仅包含整数的列表?_Python_List - Fatal编程技术网

如何删除python列表中的数字自由字符串并将其转换为仅包含整数的列表?

如何删除python列表中的数字自由字符串并将其转换为仅包含整数的列表?,python,list,Python,List,我目前正在做一个学校项目,但是我很难过滤一个由字符串和整数组成的列表。其中一个列表的输出如下所示: hours = ['Hours]', '58', '30', '44', '21', '18'] 我已尝试使用将列表中的字符串转换为整数,方法是: numhours = list(map(int, hours)) 但是,一旦看到第一个字符串,它就会失败,因为它不是一个数字。我应该如何处理删除不包含数字的字符串并将列表转换为更像以下内容的整数列表的问题: [58, 30, 44, 21, 18]

我目前正在做一个学校项目,但是我很难过滤一个由字符串和整数组成的列表。其中一个列表的输出如下所示:

hours = ['Hours]', '58', '30', '44', '21', '18']
我已尝试使用将列表中的字符串转换为整数,方法是:

numhours = list(map(int, hours))
但是,一旦看到第一个字符串,它就会失败,因为它不是一个数字。我应该如何处理删除不包含数字的字符串并将列表转换为更像以下内容的整数列表的问题:

[58, 30, 44, 21, 18]

感谢您的帮助

最简单的方法可能是编写一个生成器函数,如下所示:

def only_integers(iterable):
    for item in iterable:
        try:
            yield int(item)
        except ValueError:
            pass

numhours = list(only_integers(hours))

[int(hour)for hour in hours if hour.isdigit()]

您可以迭代循环并尝试将每个元素转换为int。如果它不起作用,我们可以捕获错误

new = []
for elements in hours:
    try:new.append(int(elements))
    except:pass
输出

[58, 30, 44, 21, 18]

res=[int(ele)for ele in hours if ele.isdigit()]只要您不需要负整数,它就可以工作。但是事实证明,这是正确的答案