📌  相关文章
📜  Python程序从字符串列表中删除除指定字母之外的每个元素

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

Python程序从字符串列表中删除除指定字母之外的每个元素

给定一个仅包含字符串元素的 List,以下程序显示了如何从元素中删除所有其他字母表(特定字母除外)然后返回输出的方法。

方法一:使用循环

在这里,我们通过仅附加 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))


输出:

方法 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))

输出: