将元素保留在另一个列表中包含的元组列表中

时间:2019-03-20 14:10:29

标签: python list

所以我有这个坏单词列表:

badWords = ["nu", "să", "o", "și", "de", "i", "pe", "cu", "ce", "mai", "la", "în", "un", "se", "mi", "eu", "ca",
                "că"]

我有这个格式的双重清单:

word_list = [(673, 'de'), (606, 'și'), (518, 'o'), (486, 'să'), (484, 'nu'), (469, 'i'), (348, 'pe'), (309, 'răzvan'), (308, 'cu'), (304, 'ce'), (302, 'mai')]

我已尝试执行此操作,以便删除与我的不良单词列表匹配的条目

for x in range(len(word_list)):
    for y in range(len(word_list[x])):
        for word in badWords:
            if(word_list[x][y] == word):
                word_list.remove(x)

但是我明白了:

  

错误:list.remove(x):x不在列表中

3 个答案:

答案 0 :(得分:3)

最好用list comprehension创建一个新列表,并只保留那些第二项不在badWords中的元组:

[i for i in word_list if i[1] not in badWords]
# [(309, 'răzvan')]

答案 1 :(得分:0)

最好不要在迭代时删除项目。 您可以这样:

for word in word_list[:]:
    if word[1] in badWords:
        word_list.remove(word)

print(word_list)
# [(309, 'răzvan')]

您可以阅读wtfpython,这可能会对您有所帮助。

答案 2 :(得分:0)

与集合相比,运算符d."field_10" = b."field_4" and d."field_11" = 1的集合处理要快得多:

local fib = {}

function fib_index(t, k)
   if k == 0 or k == 1 then
      t[k] = k
   else
      t[k] = t[k-1] + t[k-2]
   end
   return t[k]
end
setmetatable(fib, {__index = fib_index})