如何从包含其他lis关键字的嵌套列表中查找所有列表

2024-06-26 02:38:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我找不到方法从嵌套列表中获取所需的所有列表,该列表包含另一个列表中的单词。我的嵌套列表是一袋文本中的单词。你知道吗

这是我的嵌套列表的一个片段:

[['what',
  'selection',
  'in',
  'dhaka'],
 ['emergency',
  'donors',
  'in',
  'kotwali',
  'posts'],
 ['the',
  'threat',
  'monsoon',
  'progresses',
  'hitting',
  ]

这是我要与之比较/检查的列表片段(comparable_lst):

['dhaka',
 'kotwali',
 'khilkhet',
 'khilgaon',
 'demra',
 'turag']

我试过了

[i for e in bag_of_words for i in comparable_lst if e in i]

我的预期结果是:

[['what',
  'selection',
  'in',
  'dhaka'],
 ['emergency',
  'donors',
  'in',
  'dhaka',
  'posts']]

因为dhakakotwali存在于前两个列表以及comparable_lst


Tags: 方法in文本列表forcomparable单词what
1条回答
网友
1楼 · 发布于 2024-06-26 02:38:23

您可以使用一个简单的列表:

nested_lists = [['what',
  'selection',
  'in',
  'dhaka'],
 ['emergency',
  'donors',
  'in',
  'kotwali',
  'posts'],
 ['the',
  'threat',
  'monsoon',
  'progresses',
  'hitting',
  ]]

words = ['dhaka',
 'kotwali',
 'khilkhet',
 'khilgaon',
 'demra',
 'turag']

want = list(l for l in nested_lists if any(w in l for w in words))

print(want)

输出:

[['what', 'selection', 'in', 'dhaka'], ['emergency', 'donors', 'in', 'kotwali', 'posts']]

使用any函数来确定words中的任何值是否存在于nested_lists

相关问题 更多 >