📜  Python – 使用子字符串字符串列表计算字符串

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

Python – 使用子字符串字符串列表计算字符串

Python可以很容易地处理并且也被多次处理的经典问题是查找a 字符串是否是other的子字符串。但有时,人们希望将其扩展到字符串列表并找出有多少字符串满足条件,因此需要遍历整个容器并执行通用算法。让我们讨论执行此任务的某些方法。

方法 #1:使用列表理解 + len()
列表理解是执行任何特定任务的一种优雅方式,因为它从长远来看增加了可读性。此任务可以使用简单的方法执行,因此也可以简化为列表理解。 len() 用于计算列表的长度。

# Python code to demonstrate 
# Count Strings with substring String List
# using list comprehension + len()
  
# initializing list 
test_list = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
  
# printing original list 
print ("The original list is : " + str(test_list))
  
# initializing substring
subs = 'Geek'
  
# using list comprehension + len()
# Count Strings with substring String List
res = len([i for i in test_list if subs in i])
  
# printing result 
print ("All strings count with given substring are : " + str(res))
输出 :
The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
All strings count with given substring are : 2

方法 #2:使用filter() + lambda + len()
此函数还可以在 lambda 的帮助下执行查找字符串的任务。它只是过滤掉与特定子字符串匹配的所有字符串,然后将其添加到新列表中。 len() 用于计算列表的长度。

# Python code to demonstrate 
# Count Strings with substring String List
# using filter() + lambda + len()
  
# initializing list 
test_list = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
  
# printing original list 
print ("The original list is : " + str(test_list))
  
# initializing substring
subs = 'Geek'
  
# using filter() + lambda + len()
# Count Strings with substring String List
res = len(list(filter(lambda x: subs in x, test_list)))
  
# printing result 
print ("All strings count with given substring are : " + str(res))
输出 :
The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
All strings count with given substring are : 2