在没有2d列表的情况下进行双迭代



我想在for推导式中执行双'for'循环。但是,我不想在典型的条件下这样做,例如:

sentences = ['hello what are you doing?', 'trying to figure this out!']
[c for word in sentences for c in word]

相反,我想用条件来执行这个双迭代,但是在for-comprehension中:

words = ["snake", "porcupine", "lizard"]
substrings = ["sn", "o", "ke"]
new = []
for word in words:
for substr in substrings:
if substr in word:
new.append(word)
new = set(new)
print(new)

任何帮助都是感激的!

刚刚明白了,没关系。只需使用any():

new = [word for word in words if any(substr in word for substr in substrings)]

相关内容

  • 没有找到相关文章

最新更新