簡體   English   中英

如何從 python 的嵌套列表中刪除列表?

[英]How to remove a list from a nested list in python?

我正在使用 python 探索概率,我想解決這類問題。 我有 5 對夫婦,我想從這些夫婦中提取每組三人,其中不包含已婚夫婦的人。

import itertools as it

married_couples = [["Mary","John"],["Homer","Marge"],["Beauty","Beast"],["Abigail","George"],["Marco","Luisa"]]

all_persons = []
for couples in married_couples:
    for person in couples:
        all_persons.append(person)

sample_space = list(it.combinations(all_persons,3))

# Better solution with generator:
sample_space = [s for t in it.combinations(married_couples, 3) for s in it.product(*t)]

現在我想繼續從樣本空間中排除所有包含來自同一對已婚夫婦的人的結果,然后我嘗試:

correct_results = sample_space.copy()
for couple in married_couples:
    for res in sample_space:
        if couple[0] in res and couple[1] in res:
                if res in correct_results:
                    correct_results.remove(res)

編輯:我編輯並將生成器解決方案也放入其中,因此您可以為此目的使用此代碼

問題是在

if couple[0] and couple[1] in res:

因為它測試的不是這對夫婦在res中,而是這對夫婦的第一個元素不是 null 而第二個元素在res中。

你應該使用:

if couple[0] in res and couple[1] in res:

這是一種更有效的方法:

r = [s for t in itertools.combinations(married_couples, 3) for s in itertools.product(*t)]

如果您只需要迭代它,而不需要它作為實際的擴展列表,那么您可以創建一個生成器:

iter = (s for t in itertools.combinations(married_couples, 3) for s in itertools.product(*t))

然后你可以這樣做:

for triple in iter:
    ...

兩種解決方案的工作方式如下:它有兩個級別。 在頂層,它調用itertools.combinations(married_couples, 3) 這會從原始的已婚夫婦中生成所有三胞胎。 然后,對於每個三元組,它使用iterrools.product(*t)生成所有 8 種組合,這些組合從三元組中的三對中的每一對中取一個。

暫無
暫無

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

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