gpt4 book ai didi

python - 只要单词不是元组列表中的单词,如何创建单词列表

转载 作者:行者123 更新时间:2023-11-28 20:58:04 27 4
gpt4 key购买 nike

我有话要说:

wordlist = ['change', 'my', 'diaper', 'please']

我还有一个需要检查的元组列表:

mylist = [('verb', 'change'), ('prep', 'my')]

我想做的是用所有不在元组列表中的单词创建一个列表。

所以这个例子的结果是['diaper', 'please']

我试过的似乎是重复的:

[word for tuple in mylist for word in wordlist if word not in tuple]

如何尽可能高效地生成不在元组列表中的单词列表?

不使用集合。

编辑:根据 set

的以下限制选择答案

最佳答案

这是一个使用列表推导的单行代码

[word for word in wordlist if word not in [ w[1] for w in mylist ]]

内部列表,[ w[1] for w in mylist ] 从元组列表中提取第二个元素。

外部列表,[wordfor word in wordlist if word not in innerlist] 提取单词,过滤掉刚刚提取的列表中的单词。

附言我假设您只想过滤元组列表的第二个元素。

关于python - 只要单词不是元组列表中的单词,如何创建单词列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52052236/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com