📜  Python|元组字符串中的常用词

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

Python|元组字符串中的常用词

有时,在处理元组时,我们可能会遇到一个问题,即我们需要在单个元组中以字符串为元素查找出现在字符串中的单词的交集。让我们讨论一些可以解决这个问题的方法。

方法 #1:使用join() + set() + & operator + split()
上述功能的组合可用于执行此特定任务。在此,我们首先将每个元组转换为 set,然后执行split()的元素单词的交集。最后一步是使用join()连接所有常见元素。

# Python3 code to demonstrate working of
# Common words among tuple strings
# Using join() + set() + & operator + split()
  
# Initializing tuple 
test_tup = ('gfg is best', 'gfg is for geeks', 'gfg is for all')
  
# printing original tuple 
print("The original tuple is : " + str(test_tup))
  
# Common words among tuple strings
# Using join() + set() + & operator + split()
res = ", ".join(sorted(set(test_tup[0].split()) &\
          set(test_tup[1].split()) &\
          set(test_tup[2].split())))
  
# printing result
print("Common words among tuple are : " + res)
输出 :
The original tuple is : ('gfg is best', 'gfg is for geeks', 'gfg is for all')
Common words among tuple are : gfg, is

方法 #2:使用map() + reduce() + lambda
上述方法的组合也可用于执行此特定任务。在这里,我们只是结合元组的所有元素来使用 lambda 和reduce()检查公共元素。这种方法的优点是它可以轻松地处理具有多个可数元素的元组。仅适用于 Python3。

# Python3 code to demonstrate working of
# Common words among tuple strings
# Using map() + reduce() + lambda
  
# Initializing tuple 
test_tup = ('gfg is best', 'gfg is for geeks', 'gfg is for all')
  
# printing original tuple 
print("The original tuple is : " + str(test_tup))
  
# Common words among tuple strings
# Using map() + reduce() + lambda
res = ", ".join(reduce(lambda i, j : i & j, 
                map(lambda x: set(x.split()), test_tup)))
  
# printing result
print("Common words among tuple are : " + res)
输出 :
The original tuple is : ('gfg is best', 'gfg is for geeks', 'gfg is for all')
Common words among tuple are : gfg, is