📜  Python - 用数字提取字符串

📅  最后修改于: 2022-05-13 01:54:32.072000             🧑  作者: Mango

Python - 用数字提取字符串

给定一个字符串列表,提取至少一位数的字符串。

方法 #1:使用列表理解+ any() + isdigit()

在此迭代中,每个字符串的迭代都是使用列表理解完成的,any() 和 isdigit() 用于检查至少一个数字的任务。

Python3
# Python3 code to demonstrate working of
# Extract Strings with a digit
# Using list comprehension + any() + isdigit()
 
# initializing list
test_list = ['gf4g', 'is', 'best', '4', 'gee1ks']
 
# printing original list
print("The original list is : " + str(test_list))
 
# checking if string contain any string using any()
res = [sub for sub in test_list if any(ele for ele in sub if ele.isdigit())]
 
# printing result
print("Strings with any digit : " + str(res))


Python3
# Python3 code to demonstrate working of
# Extract Strings with a digit
# Using any() + filter() + lambda
 
# initializing list
test_list = ['gf4g', 'is', 'best', '4', 'gee1ks']
 
# printing original list
print("The original list is : " + str(test_list))
 
# checking if string contain any string using any()
# filter() used to filter strings with digits
res = list(filter(lambda sub: any(
    ele for ele in sub if ele.isdigit()), test_list))
 
# printing result
print("Strings with any digit : " + str(res))


输出:

方法#2:使用 any() + filter() + lambda

在这里,我们使用 lambda 和 filter() 执行过滤任务,其余保持不变。

蟒蛇3

# Python3 code to demonstrate working of
# Extract Strings with a digit
# Using any() + filter() + lambda
 
# initializing list
test_list = ['gf4g', 'is', 'best', '4', 'gee1ks']
 
# printing original list
print("The original list is : " + str(test_list))
 
# checking if string contain any string using any()
# filter() used to filter strings with digits
res = list(filter(lambda sub: any(
    ele for ele in sub if ele.isdigit()), test_list))
 
# printing result
print("Strings with any digit : " + str(res))

输出: