簡體   English   中英

如何在不更改原始列表的情況下使變量等於刪除了項目的列表?

[英]How to make a variable equal to a list with items removed, without changing original list?

我試圖從列表中刪除刪除項,然后使其與另一個變量相等,同時仍保留原始列表。

碼:

print (len(desc1))
desc2 = []
for tuple in desc1:
    for line in tuple:
        if line.endswith(':'):
            desc2 = desc1.remove(tuple)
print (len(desc1))
print (desc2)

輸出:

550 
200
None

我想要的輸出是:

550
550
200

我必須使用什么來實現這一目標?

首先復制列表。

desc2 = desc1[:]  # shallow copy
for tuple in desc2:
    for line in tuple:
        if line.endswith(":"):
            desc2.remove(tuple)  # don't assign here

請注意,無論如何這都是一個壞主意,因為在迭代列表時會對其進行變異(刪除成員)。 另外,您正在使用list.remove數以百計,而且速度並不很快。 而是考慮使用列表推導。

desc2 = [tup for tup in desc1 if not any(line.endswith(":") for line in tup)]
# or
desc2 = filter(lambda t: not any(line.endswith(":") for line in t), desc1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM