📜  Python - 矩阵中的可成形字符串计数

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

Python - 矩阵中的可成形字符串计数

给定字符串矩阵,任务是编写一个Python程序来计算可以由给定列表中的字母组成的字符串。

例子:

方法#1:使用loop + all()

在此,我们使用 for 循环执行循环迭代任务,all() 用于检查字符串的每个元素是否包含目标列表中的所有字母。如果找到,则计数器递增。

Python3
# Python3 code to demonstrate working of
# Formable Strings Count in Matrix
# Using loop
  
# initializing list
test_list = [["gfg", "best"], ["all", "love", "gfg"],
             ["gfg", "is", "good"], ["geeksforgeeks"]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing target list
tar_list = ["g", "f", "s", "b", "o", "d", "e", "t"]
  
res = 0
for sub in test_list:
    for ele in sub:
  
        # checking for all elements present using all()
        if all(el in tar_list for el in ele):
            res += 1
  
# printing result
print("The computed count : " + str(res))


Python3
# Python3 code to demonstrate working of
# Formable Strings Count in Matrix
# Using list comprehension + all() + sum()
  
# initializing list
test_list = [["gfg", "best"], ["all", "love", "gfg"],
             ["gfg", "is", "good"], ["geeksforgeeks"]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing target list
tar_list = ["g", "f", "s", "b", "o", "d", "e", "t"]
  
# computing summation using sum()
# list comprehension used to provide one liner solution
res = sum([sum([1 for ele in sub if all(el in tar_list for el in ele)])
           for sub in test_list])
  
# printing result
print("The computed count : " + str(res))


输出:

方法 #2:使用列表理解+ all() + sum()

在这里,问题使用列表推导在一行中解决,all() 用于检查是否存在所有字符,sum() 用于计算字符串过滤后的字符串数。

蟒蛇3

# Python3 code to demonstrate working of
# Formable Strings Count in Matrix
# Using list comprehension + all() + sum()
  
# initializing list
test_list = [["gfg", "best"], ["all", "love", "gfg"],
             ["gfg", "is", "good"], ["geeksforgeeks"]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing target list
tar_list = ["g", "f", "s", "b", "o", "d", "e", "t"]
  
# computing summation using sum()
# list comprehension used to provide one liner solution
res = sum([sum([1 for ele in sub if all(el in tar_list for el in ele)])
           for sub in test_list])
  
# printing result
print("The computed count : " + str(res))

输出: