【问题标题】:Find elements of 2 lists in a string in python在python中的字符串中查找2个列表的元素
【发布时间】:2016-01-04 14:11:05
【问题描述】:
list1 = ['abra','hello','cfre']

list2 = ['dacc','ex','you', 'fboaf']

ttext = 'hello how are you?'

for i,j in zip(list1, list2):
    print i,j

abra dacc
hello ex
cfre you
None fboaf

if (i in ttext and j in ttext):

你好,这个比较列表的相同索引,这里我想查找 ttext 中是否有 'hello' 和 'you'

最好的方法是什么?

【问题讨论】:

  • 什么是怪胎 'if (i in ttext and j in text):' ?这是语法错误。

标签: python string python-2.7 enumerate


【解决方案1】:

你可以像这样使用itertools.product

>>> list1 = ['abra', 'hello', 'cfre']
>>> list2 = ['dacc', 'ex', 'you', 'fboaf']
>>> ttext = 'hello how are you?'
>>> from itertools import product
>>> for word1, word2 in product(list1, list2):
...     print word1, word2, (word1 in ttext and word2 in ttext)
...
abra dacc False
abra ex False
abra you False
abra fboaf False
hello dacc False
hello ex False
hello you True
hello fboaf False
cfre dacc False
cfre ex False
cfre you False
cfre fboaf False

itertools.product 计算传递给它的迭代的笛卡尔积。现在,我们检查 product 中的所有项目是否都出现在 ttext 中。


您实际上可以像这样使其通用

>>> ttext = 'hello how are you?'
>>> for words in product(list1, list2):
...     print(words, all(word in ttext for word in words))

all 函数只有在传递给它的可迭代对象的所有元素都是真值时才会返回 True。在您的情况下,它只是检查 words 元组中的每个单词是否存在于 ttext 中。

【讨论】:

  • for word1, word2 in product(list1, list2): if (word1 in ttext and word2 in ttext): print 'ok'
  • 使用it.product(*((word for word in lst if word in ttext) for lst in (list1, list2)))应该更快,因为它首先过滤正确的词然后计算产品。此外,word in ttext 不是正确的单词测试,因为它也匹配 hello 中的 ell。将ttext 转换为字符串列表,例如re.findall(r'\w+', ttext)
  • @thefourtheye 现在如果我有超过 2 个列表,例如,我有一个列表列表,我想确保我只有一个列表中的一个词?
  • @supertrainee 您可以使用我在底部提到的通用方法,只需稍作改动。 for words in product(*list_of_lists):
  • @supertrainee 我无法打开它
猜你喜欢
  • 2022-10-19
  • 2021-03-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多