📜  用标点符号对字符串进行排序的Python程序

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

用标点符号对字符串进行排序的Python程序

给定字符串列表,按标点符号数排序。

方法 #1:使用字符串.punctuation + sort()

在这种情况下,排序是使用 sort() 完成的,标点符号是从字符串库的标点符号池中提取的。执行就地排序。

Python3
# Python3 code to demonstrate working of
# Sort Strings by Punctuation count
# Using string.punctuation + sort()
from string import punctuation
 
def get_pnc_count(string):
     
    # getting punctuation count
    return len([ele for ele in string if ele in punctuation])
 
# initializing list
test_list = ["gfg@%^", "is", "Best!", "fo@#r", "@#$ge24eks!"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# performing inplace sort
test_list.sort(key = get_pnc_count)
 
# printing result
print("Sorted Strings list : " + str(test_list))


Python3
# Python3 code to demonstrate working of
# Sort Strings by Punctuation count
# Using sorted() + punctuation + lambda
from string import punctuation
 
# initializing list
test_list = ["gfg@%^", "is", "Best!", "fo@#r", "@#$ge24eks!"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# performing sort using sorted() with lambda
# function for filtering
res = sorted(test_list, key=lambda string: len(
    [ele for ele in string if ele in punctuation]))
 
# printing result
print("Sorted Strings list : " + str(res))


输出:

方法 #2:使用sorted() + 标点符号 + lambda

在此,我们使用 lambda 使用 sorted() 执行排序,以避免外部函数执行过滤使用标点提取的标点的任务。

蟒蛇3

# Python3 code to demonstrate working of
# Sort Strings by Punctuation count
# Using sorted() + punctuation + lambda
from string import punctuation
 
# initializing list
test_list = ["gfg@%^", "is", "Best!", "fo@#r", "@#$ge24eks!"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# performing sort using sorted() with lambda
# function for filtering
res = sorted(test_list, key=lambda string: len(
    [ele for ele in string if ele in punctuation]))
 
# printing result
print("Sorted Strings list : " + str(res))

输出: