簡體   English   中英

使用python list comprehensions從列表中刪除項目

[英]Remove items from list by using python list comprehensions

我有一個整數列表,如下所示:

unculledlist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

我想剔除這個列表中的值,所以它看起來像這樣:

culledlist = [0, 2, 4, 10, 12, 14, 20, 22, 24]

但我想通過使用列表推導來做到這一點。

這是我試圖剔除列表值的圖形預覽。 如果我將列表值排列成行和列,則更容易理解。 但這只是視覺上的。 我不需要嵌套列表: 在此輸入圖像描述

我可以通過使用兩個嵌套循環來完成它:

unculledlist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

index = 0
culledlist = []
for i in range(6):
    for j in range(5):
        if (i % 2 == 0) and (j % 2 == 0):
            culledlist.append(unculledlist[index])
        index += 1

print "culledlist: ", culledlist  # culledlist = [0, 2, 4, 10, 12, 14, 20, 22, 24]

但我想用python列表理解來代替它。

有人可以提供一個例子嗎?

謝謝。

編輯:

我想使用列表unculledlist的原因是因為我的實際unculledlist列表有幾百萬個整數。 使用列表推導解決這個問題將最終加快速度。 我不在乎可讀性。 我只是想做一個更快的解決方案。

我不能使用numpy或scipy模塊。 但我可以使用itertools模塊。 不確定使用itertools的解決方案是否比具有列表推導的解決方案更快? 甚至是lambda

我看到了這一點,並認為字符串操作將是更容易的方法

culled_list = [item for item in unculledlist if str(item)[-1] in ['0','2','4']]

結果仍然是整數列表

>>> culled_list
[0, 2, 4, 10, 12, 14, 20, 22, 24]

感謝eugene y采用不那么復雜的方法

>>> culled_list = [item for item in unculledlist if item % 10 in (0,2,4)]
>>> culled_list
[0, 2, 4, 10, 12, 14, 20, 22, 24]

你可以用這樣的列表理解來做到這一點:

[x for i, x in enumerate(unculledlist) if (i % 6) % 2 == 0 if (i % 5) % 2 == 0]

輸出是:

[0, 2, 4, 10, 12, 14, 20, 22, 24]

您可以在5個項目塊中讀取列表,並從每個偶數塊中提取偶數索引的元素:

>>> [x for i, v in enumerate(range(0, len(unculledlist), 5)) if not v % 2 for x in unculledlist[v:v+5:2]]
[0, 2, 4, 10, 12, 14, 20, 22, 24]
culledlist = [num for num in unculledlist if not (num / 5) % 2 and not num % 2]

當我分析模式時,我意識到排除5,15,25的行。 我做到了;

(num / 5) % 2

每行返回1,如[5,6,7,8,9]或[15,16,17,18,19]

在其他行(從上面的等式返回0)中,從0,10,20開始並未完全排除,而是僅排除了奇數值。 我這樣做是用的;

num % 2
# Returns zero with even values.

因為第一個等式已經滿足,所以取基本num%2可以正常工作。 我沒有使用任何;

==
# A logical operator

因為0和1已經作為布爾值。

暫無
暫無

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

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