![](/img/trans.png)
[英]Is there a built-in function to sort and filter a python list in one step?
[英]Python built-in list: remove one item
lst = [(32,(4,5)),(55,(5,6))]
給定一個元組(4,5),所以我想刪除lst中的第一個元組。 怎么做?
抱歉,目前還不清楚,我的意思是在每個列表項中的第二項之前刪除列表項
lst2 = [(x, y) for (x, y) in lst if y != (4, 5)]
刪除所有(4、5)元組,而不僅僅是第一個實例。
您可以過濾列表:
lst = filter(lambda x, y: y != (4,5), lst)
這將刪除第一個與第二個組件匹配的列表條目,但不要使用它來刪除多個列表條目。 要執行多個操作,請使用其他列表建議的列表comp或在列表的副本上進行迭代(對於eaxmple: for n in L[:]
)。 修改要迭代的列表會產生意外的結果。
>>> def remove(L,t):
... for n in L:
... if n[1]==t:
... L.remove(n)
... break
...
>>> L=[(1,(2,3)),(4,(5,6)),(7,(2,3))]
>>> remove(L,(2,3))
>>> L
[(4, (5, 6)), (7, (2, 3))]
您是說lst2 = [(a,) for (a,b) in lst]' ?
That will result inlst2 = [(a,) for (a,b) in lst]' ?
That will result inlst2 = [(a,) for (a,b) in lst]' ?
[(32,),(55,)]`
That will result in
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.