📌  相关文章
📜  Python – 删除大于 K 的字符

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

Python – 删除大于 K 的字符

给定字符串列表,从每个字符串中删除所有字符大于 K 的字符。

方法 #1:使用循环 + ord()

在此,我们使用ord()检查字符的ASCII值,然后与K进行比较,如果字符大于K,则该字符不包含在结果字符串中。

Python3
# Python3 code to demonstrate working of
# Remove characters greater than K
# Using loop + ord()
 
# initializing list
test_list = ["geeksforgeeks", "is", "best", "for", "geeks"]
 
# printing original lists
print("The original list is : " + str(test_list))
 
# initializing K
K = 13
 
res = []
for ele in test_list:
    res_str = ''
    for sub in ele:
         
        # check for string characters
        if (ord(sub) - 97 <= K):
            res_str += sub
    res.append(res_str)
 
# printing result
print("Filtered List " + str(res))


Python3
# Python3 code to demonstrate working of
# Remove characters greater than K
# Using join() + list comprehension + ord()
 
# initializing list
test_list = ["geeksforgeeks", "is", "best", "for", "geeks"]
 
# printing original lists
print("The original list is : " + str(test_list))
 
# initializing K
K = 13
 
# using list comprehension for 1 liner
res = [''.join([ele for ele in sub if ord(ele) - 97 <= K]) for sub in test_list]
 
# printing result
print("Filtered List " + str(res))


输出:

方法 #2:使用 join() + 列表推导 + ord()

这是可以执行此任务的速记方式。在此,我们使用 join() 执行过滤和连接以形成字符串的任务。

蟒蛇3

# Python3 code to demonstrate working of
# Remove characters greater than K
# Using join() + list comprehension + ord()
 
# initializing list
test_list = ["geeksforgeeks", "is", "best", "for", "geeks"]
 
# printing original lists
print("The original list is : " + str(test_list))
 
# initializing K
K = 13
 
# using list comprehension for 1 liner
res = [''.join([ele for ele in sub if ord(ele) - 97 <= K]) for sub in test_list]
 
# printing result
print("Filtered List " + str(res))

输出: