如何迭代元组列表的第一个元素



我有一个元组列表,所有元组都包含1个短语和1个数字。

示例:[('light blue', 3), ('light green', 4), ('blue shade', 2), ('deep red', 3), ('dark red')]

我想从列表中删除包含某些单词的元组。

假设我想删除短语中包含"blue"或"dark"的元组。我该怎么做?

我试过了,但没有成功:

for x in Example:
if 'blue' in x[0] or 'dark' in x[0]:
Example.remove(x)

您可以在python中使用名为filter的东西。您可以创建一个名为lambda的匿名函数,该函数将检查列表中的每个第一个元素,并根据该函数返回的布尔值,它将保留或丢弃该值。

lst = [('light blue', 3), ('light green', 4), ('blue shade', 2), ('deep red', 3), ('dark red')]
list(filter(lambda x: 'blue' not in x[0], lst))

您可以创建remove_list,然后使用any进行检查,并从原始列表中删除元素,如下所示:

>>> lst = [('light blue', 3), ('light green', 4), ('blue shade', 2), ('deep red', 3), ('dark red', 1)]
>>> rm_lst = ['blue', 'dark']
>>> [l for l in lst if not any(r_l in l[0] for r_l in rm_lst)]
[('light green', 4), ('deep red', 3)]

由于我们有内部数据,我们必须先到外部数据的索引,然后到内部数据的索引。为此,首先迭代外部数据for i in example,这样每个值现在都将是一个元组,然后使用i[0]进行比较。如果条件满足,则删除整个元组,即i.您的代码:

Example=[('light blue', 3), ('light green', 4), ('blue shade', 2), ('deep red', 3), ('dark red',)]      #write a comma at the end of (dark red) tuple because it will consider it as string until there's a comma at the end
x=Example.copy()
for i in x:        #i values will be inner tuples
if "blue" in i [0] or "dark" in i[0]:
Example.remove(i)       #removing the tuple
print(Example)

最新更新