【问题标题】:How to iterate through the first elements of a list of tuples? [duplicate]如何遍历元组列表的第一个元素? [复制]
【发布时间】:2021-11-03 12:45:38
【问题描述】:

我有一个元组列表,都包含 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)

【问题讨论】:

  • 最后一个元素dark red没有数字?
  • @user1740577 提出了一个重要问题。目前,最后一项是 str 而不是元组。要使其成为实际的元组(即使没有第二个值),您需要('dark red',)。如果允许一个字符串,那么它将影响答案。

标签: python list tuples


【解决方案1】:

您可以在 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))

【讨论】:

    【解决方案2】:

    您可以创建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)]
    

    【讨论】:

      【解决方案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)
      

      【讨论】:

      • 你真的不想从你这样迭代的列表中remove()。尝试通过将if "blue" in i[0] 切换为红色来移除红色。
      • 是的,我试过了,没用。我能知道为什么吗??条件不满足?? “红色”在最后一个,但它没有被删除
      • 当您从列表中删除项目时,循环与您可能认为“当前”项目所在的位置不同步。通常,您会希望使用范围并从末尾向后迭代,以便在删除项目时索引不会混乱。
      • 好的,如果我创建列表的.copy() 并遍历复制的列表但从原始列表中删除怎么办?这行得通吗?
      • 不不,如果你使用 .copy() 那么复制列表中的更改不会在原始列表中进行更改。我已经编辑了我的答案,请复制并执行它并告诉我
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-08
      • 2016-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-10
      相关资源
      最近更新 更多