Python程序从字符串列表中删除除指定字母之外的每个元素
给定一个仅包含字符串元素的 List,以下程序显示了如何从元素中删除所有其他字母表(特定字母除外)然后返回输出的方法。
Input : test_list = [“google”, “is”, “good”, “goggled”, “god”], K = ‘g’
Output : [‘gg’, ”, ‘g’, ‘ggg’, ‘g’]
Explanation : All characters other than “g” removed.
Input : test_list = [“google”, “is”, “good”, “goggled”, “god”], K = ‘o’
Output : [‘oo’, ”, ‘oo’, ‘o’, ‘o’]
Explanation : All characters other than “o” removed.
方法一:使用循环
在这里,我们通过仅附加 K 并避免结果中的所有其他字符串来重新制作字符串 。
Python3
# initializing list
test_list = ["google", "is", "good", "goggled", "god"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 'g'
res = []
for sub in test_list:
# joining only K characters
res.append(''.join([ele for ele in sub if ele == K]))
# printing result
print("Modified List : " + str(res))
Python3
# initializing list
test_list = ["google", "is", "good", "goggled", "god"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 'g'
# appending and joining using list comprehension and join()
res = [''.join([ele for ele in sub if ele == K]) for sub in test_list]
# printing result
print("Modified List : " + str(res))
输出:
The original list is : [‘google’, ‘is’, ‘good’, ‘goggled’, ‘god’]
Modified List : [‘gg’, ”, ‘g’, ‘ggg’, ‘g’]
方法 2:使用列表推导和join()
在这里,我们使用列表推导式执行重新创建列表的任务,然后 join() 可以连接所有出现的 K。
蟒蛇3
# initializing list
test_list = ["google", "is", "good", "goggled", "god"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 'g'
# appending and joining using list comprehension and join()
res = [''.join([ele for ele in sub if ele == K]) for sub in test_list]
# printing result
print("Modified List : " + str(res))
输出:
The original list is : [‘google’, ‘is’, ‘good’, ‘goggled’, ‘god’]
Modified List : [‘gg’, ”, ‘g’, ‘ggg’, ‘g’]