【问题标题】:Create a list of tuples excluding on tuple in the list创建一个元组列表,不包括列表中的元组
【发布时间】:2014-03-04 01:10:07
【问题描述】:

我有一个元组列表,我想创建另一个不包含该列表中特定元组的列表。

例子:

mylist = [(a,b), (c,d), (e,f)]  
selected = (c,d)  
operation_between(list, selected)  
newlist = [(a,b), (e,f)]

最简单的方法是使用 for 循环,用于遍历 mylist 并在 current_item != selected 时插入到 newlist。有没有更好的办法?

我想将列表转换为集合,然后使用- 运算符从集合中删除选定的元组。但是使用set(mylist) 只创建了一个包含一个项目的集合,即列表。
然后解决这个问题,我认为使用列表推导,但这又意味着一个 for 循环。

【问题讨论】:

    标签: list python-2.7 set


    【解决方案1】:

    也许只是对您不想要的内容进行列表理解过滤?

    mylist2 = [(x, y) for (x, y) in mylist if (x, y) != (c, d)]

    【讨论】:

    • 如果newlist 必须是副本,则为列表理解+1。顺便说一句,您不需要解压缩元组:newlist = [item for item in mylist if item != selected]
    【解决方案2】:

    如果您想更改mylist,请使用list.remove()

    mylist.remove(selected)
    

    如果您想要一个没有相关元素的 mylist 的新副本,请改用 list() 构造函数创建一个新列表,然后在新列表上调用 remove()

    newlist = list(mylist)
    newlist.remove(selected)
    

    【讨论】:

    • 如果必须就地修改 mylist,则为 list.remove +1。
    猜你喜欢
    • 1970-01-01
    • 2013-09-10
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 2020-12-15
    相关资源
    最近更新 更多