本文概述
给定一个仅包含字符串元素的List, 下面的程序演示了如何从元素中除去除特定字母之外的所有其他字母, 然后返回输出的方法。
输入:test_list = [“google”, “is”, “good”, “goggled”, “god”], K =’g’
输出:[‘gg’, “, ‘g’, ‘ggg’, ‘g ‘]
说明:除去”g”以外的所有字符。
输入:test_list = [“google”, “is”, “good”, “goggled”, “god”], K =’o’
输出:[‘oo’, “, ‘oo’, ‘o’, ‘o ‘]
说明:除去”o”以外的所有字符。
方法1:使用循环
在此, 我们通过仅附加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))
输出如下:
原始列表是:[‘google’, ‘is’, ‘good’, ‘goggled’, ‘god’]
修改后的列表:[‘gg’, “, ‘g’, ‘ggg’, ‘g’]
方法2:使用清单理解和加入()
在此, 我们使用列表理解执行重新创建列表的任务, 然后join()可以将所有出现的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'
# 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))
输出如下:
原始列表是:[‘google’, ‘is’, ‘good’, ‘goggled’, ‘god’]
修改后的列表:[‘gg’, “, ‘g’, ‘ggg’, ‘g’]
首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。
评论前必须登录!
注册