簡體   English   中英

對列表元素進行迭代而沒有冗余; 蟒蛇

[英]Iteration over elements of a list without redundancy; Python

我有一個搜索字符串,例如

string = [1,2,3]

和一個樣本

sample = [[1,5,5,5,5,5],[2,5,5,5,5,5],[3,5,5,5,2],[4,5,5,5,5,5],[5,5,5,5,5]]

現在,我想要的是如果列表中的元素之一在string中,則將列表追加到列表的sample列表中

如果我只是簡單地遍歷sample列表的每個元素,那么我會得到很多冗余:

accepted = []
rejected = []

for list in sample:
    for e in list:
        if e in string:
            accepted.append(list)
        else:
            rejected.append(list)


accepted
Out: [[1, 5, 5, 5, 5, 5], [2, 5, 5, 5, 5, 5], [3, 5, 5, 5, 2], [3, 5, 5, 5, 2]]

len(rejected)
Out: 23

我需要的是僅將列表附加一次,具體取決於其元素是否為string 例如,

accepted
Out: [[1, 5, 5, 5, 5, 5], [2, 5, 5, 5, 5, 5], [3, 5, 5, 5, 2]]
rejected
Out: [[4,5,5,5,5,5],[5,5,5,5,5]]

但是無法理解如何循環執行。

另一個答案根據您的解決方案提出了一種正確的方法,這是一種更Python化的方法,您可以將string保留在set並在列表set.intersection使用set.intersection方法以獲取可接受的項目:

>>> string = {1,2,3}
>>> [i for i in sample if string.intersection(i)]
[[1, 5, 5, 5, 5, 5], [2, 5, 5, 5, 5, 5], [3, 5, 5, 5, 2]]

只需檢查它是否已插入已接受或拒絕中,而不是最佳性能即可:

for list in sample:
    if list not in accepted and list not in rejected:
        for e in list:
            if e in string:
                accepted.append(list)
                break
            elif list not in rejected:
                rejected.append(list)

您可以使用Python集快速確定每個樣本中是否存在搜索中的任何元素,如下所示:

search = set([1, 2, 3])
sample = [[1,5,5,5,5,5],[2,5,5,5,5,5],[3,5,5,5,2],[4,5,5,5,5,5],[5,5,5,5,5]]

accepted = []
rejected = []

for x in sample:
    if set(x) & search:
        accepted.append(x)
    else:
        rejected.append(x)

print accepted
print rejected             

這將顯示:

[[1, 5, 5, 5, 5, 5], [2, 5, 5, 5, 5, 5], [3, 5, 5, 5, 2]]
[[4, 5, 5, 5, 5, 5], [5, 5, 5, 5, 5]]

暫無
暫無

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

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