当两个列表中都有重复元素时,列表理解
我想找到所有具有一组特定目标字母的单词。当目标中的字母没有重复时,我的代码工作起来,但如果有重复。
这是我的代码:
target = 'bba'
target_words = [
'aani', 'aaru', 'abac', 'abas',
'abba', 'abby', 'abed', 'abel', 'abet'
]
target_list = list(target)
final_list = []
for word in target_words:
word_list = list(word)
if (all(x in word_list for x in target_list)):
final_list.append(word)
print('Final list: ', final_list)
输出是最终列表:['abac','abas','abba','abby','abed','abed','abel','abet']
我想要它为最终列表:['abba','abby']
我找不到一种方法来获得我想要的结果。这可能是因为我将单词字母转换为列表,但我看不到该怎么做。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是
collections.counter()
的好用例。它为我们提供了一种干净的方法来检查target_words
和target
的单词之间是否存在所需的重叠,请考虑重复的字母(并提出了 azro ):此输出:
This is a good use case for
collections.Counter()
. It gives us a clean way to check whether the desired overlap exists between a word intarget_words
and thetarget
, accounting for duplicate letters (with a suggested improvement by azro):This outputs:
首先,让我们在目标词中找到独特的字母。
现在,我们可以使用词典理解来获取每个字母的计数。
现在,我们需要一个列表理解,该列表可以通过
target_words
进行迭代,并检查计数中的每个字母
中的每个字母,该字母的相同数字(或更多)在目标单词中。结果:
First let's find the unique letters in your target word.
Now, we can use a dictionary comprehension to get a count of each letter.
Now we need a list comprehension that iterates over
target_words
and checks that for every letter incounts
, the same number (or more) of that letter is in the target word.Result: