[英]Write a function that will take as input a string that includes both letters and numbers
The function should first remove all of the letters, and then convert each digit to a single-digit integer. Finally, it should return a list with each of the integers sorted from lowest to highest. function 应首先删除所有字母,然后将每个数字转换为单个数字 integer。最后,它应返回一个列表,其中每个整数按从低到高排序。
("a2fei34bfij1") should return [1, 2, 3, 4] ("a2fei34bfij1") 应该返回 [1, 2, 3, 4]
("owifjaoei3oij444kfj2fij") should return [2, 3, 4, 4, 4] ("owifjaoei3oij444kfj2fij") 应该返回 [2, 3, 4, 4, 4]
("987321a") should return [1, 2, 3, 7, 8, 9] ("987321a") 应该返回 [1, 2, 3, 7, 8, 9]
One of the several ways is using regex, see if this helps几种方法之一是使用正则表达式,看看这是否有帮助
import re
regex="(?P<numbers>\d)"
def filter_digits(words):
num=[]
if words:
m = re.findall(regex,words)
num=sorted([int(i) for i in m])
return num
print(filter_digits("a2fei34bfij1"))
print(filter_digits("owifjaoei3oij444kfj2fij"))
print(filter_digits("987321a"))
print(filter_digits(None))
print(filter_digits("abcd"))
Reference: https://docs.python.org/3/library/re.html参考资料: https://docs.python.org/3/library/re.html
Use regex and a sort:使用正则表达式和排序:
import re
def clean_up(input_string):
return sorted(re.findall("[0-9]", input_string))
Here is my solution这是我的解决方案
import re
def intList(text):
# use regex to find every single digit in the string
numRe = re.compile(r'\d')
# use list comprehension to transform every found digit (which is string at first) to integer and make a list
mo = [int(i) for i in numRe.findall(str(text))]
# return sorted list of integers
return sorted(mo)
print(intList("a2fei34bfij1")) # prints [1, 2, 3, 4]
print(intList("owifjaoei3oij444kfj2fij")) # prints [2, 3, 4, 4, 4]
print(intList("987321a")) # prints [1, 2, 3, 7, 8, 9]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.