用标点符号对字符串进行排序的Python程序
给定字符串列表,按标点符号数排序。
Input : test_list = [“gfg@%^”, “is”, “Best!”]
Output : [‘is’, ‘Best!’, ‘gfg@%^’]
Explanation : 0 < 1 < 3, sorted by punctuation count.
Input : test_list = [“gfg@%^”, “Best!”]
Output : [ ‘Best!’, ‘gfg@%^’]
Explanation : 1 < 3, sorted by punctuation count.
方法 #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))
输出:
The original list is : [‘gfg@%^’, ‘is’, ‘Best!’, ‘fo@#r’, ‘@#$ge24eks!’]
Sorted Strings list : [‘is’, ‘Best!’, ‘fo@#r’, ‘gfg@%^’, ‘@#$ge24eks!’]
方法 #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))
输出:
The original list is : [‘gfg@%^’, ‘is’, ‘Best!’, ‘fo@#r’, ‘@#$ge24eks!’]
Sorted Strings list : [‘is’, ‘Best!’, ‘fo@#r’, ‘gfg@%^’, ‘@#$ge24eks!’]