gpt4 book ai didi

python - 根据元素值从嵌套列表中删除子列表

转载 作者:太空宇宙 更新时间:2023-11-03 17:04:14 32 4
gpt4 key购买 nike

我正在尝试根据元素值从嵌套列表中删除子列表。

data = [['1', 'i like you'],
['2', 'you are bad'],
['5', 'she is good'],
['7', 'he is poor']]

negative_words = set(['poor', 'bad'])

如果第二列包含否定词,我想删除子列表。因此,期望的结果如下。有什么建议吗?

data = [['1', 'i like you'],
['5', 'she is good']]

最佳答案

我很容易想到两种方法。

>>> data = [['1', 'i like you'], ['2', 'you are bad'],
['5', 'she is good'], ['7', 'he is poor']]
>>> neg_words = {'poor', 'bad'}

使用将子列表中的字符串转换为集合,然后检查是否为 disjointneg_words,像这样

>>> [[n, ws] for n, ws in data if set(ws.split()).isdisjoint(neg_words)]
[['1', 'i like you'], ['5', 'she is good']]

或者简单地检查列表中字符串中的单词是否不在 neg_words 中,如下所示

>>> [[n, ws] for n, ws in data if all(w not in neg_words for w in ws.split())]
[['1', 'i like you'], ['5', 'she is good']]

关于python - 根据元素值从嵌套列表中删除子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34734761/

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