从数字和字母列表中删除字母

2024-04-19 13:46:57 发布

您现在位置:Python中文网/ 问答频道 /正文

在我试图编写的函数中,用户输入一组数字,例如“648392”。 我将这个字符串转换成这样的列表:['6','4','8','3','9','2']。在

我想用这些数字求和,所以我把列表中的数字变成整数而不是字符串。这一切都很好,但是我也希望用户能够输入字母,然后我就把它们从列表中删除了——这就是我遇到的问题。例如,用户输入“6483A2”。在

我不能用isDigit检查元素是否是数字,因为元素显然必须首先是整数,而且我不能将列表中的元素转换为整数,因为有些元素是字母。。。我相信有一个简单的解决方案,但是我在python上的表现非常糟糕,所以如果有任何帮助,我将不胜感激!在


Tags: 函数字符串用户元素列表字母数字整数
3条回答

您可以使用filter函数或理解从任何iterable(包括字符串)中筛选出内容。例如,以下两种情况之一:

digits = filter(str.isdigit, input_string)
digits = (character for character in input_string if character.isdigit())

…会给你一大堆数字。如果要将每个数字转换为数字,则可以使用以下任一方法:

^{pr2}$

因此,要获得所有数字的总和,跳过字母,只需将其中一个传递给sum函数:

total = sum(map(int, filter(str.isdigit, input_string)))
total = sum(int(character) for character in input_string if character.isdigit())

从你的最后一段:

I can't check to see if an element is a digit with isDigit because the elements apparently have to be integers first, and I can't convert the elements in the list to integers

首先,它是isdigit,而不是{}。其次,isdigit是一个字符串方法,而不是整数,所以你错误地认为不能在字符串上调用它。实际上,在将字符串转换为整数之前,必须对字符串调用它。在

但这确实带来了另一个选择。在Python中,它通常是Easier to Ask Forgiveness than Permission。我们不必考虑是否可以将每个字母转换为int,然后再进行转换,而只需尝试将其转换为int,然后处理可能的失败。例如:

def get_numbers(input_string):
    for character in input_string:
        try:
            yield int(character)
        except TypeError:
            pass

现在,只是:

total = sum(get_numbers(input_string))

你可以理解:

>>> s = "6483A2"
>>> [int(c) for c in s if c.isdigit()]
[6, 4, 8, 3, 2]
>>> sum(int(c) for c in s if c.isdigit())
23

如果您想从混合字符串直接转到只包含整数的列表,那么这种方法是很好的,这可能是您的目标。在

您可以使用str.translate筛选出字母:

>>> from string import letters
>>> strs = "6483A2"
>>> strs.translate(None, letters)
'64832'

不需要将字符串转换为列表,可以迭代字符串本身。在

{and{cd2>使用 ^{pr2}$

或者您想要的数字sum

sum(int(c) for c in strs if c.isdigit())

时间比较:

细绳:

>>> strs = "6483A2"
>>> %timeit sum(int(c) for c in strs.translate(None, letters))
100000 loops, best of 3: 9.19 us per loop
>>> %timeit sum(int(c) for c in strs if c.isdigit())
100000 loops, best of 3: 10.1 us per loop

大字符串:

>>> strs = "6483A2"*1000
>>> %timeit sum(int(c) for c in strs.translate(None, letters))
100 loops, best of 3: 5.47 ms per loop
>>> %timeit sum(int(c) for c in strs if c.isdigit())
100 loops, best of 3: 8.54 ms per loop

最坏情况,所有字母:

>>> strs = "A"*100
>>> %timeit sum(int(c) for c in strs.translate(None, letters))
100000 loops, best of 3: 2.53 us per loop
>>> %timeit sum(int(c) for c in strs if c.isdigit())
10000 loops, best of 3: 24.8 us per loop
>>> strs = "A"*1000
>>> %timeit sum(int(c) for c in strs.translate(None, letters))
100000 loops, best of 3: 7.34 us per loop
>>> %timeit sum(int(c) for c in strs if c.isdigit())
1000 loops, best of 3: 210 us per loop

相关问题 更多 >