簡體   English   中英

如何操作嵌套列表

[英]how to manipulate nested lists

所以我目前有一個嵌套列表。

org_network=[[1, 2, 3], [1, 4, 5], [1, 3, 6], [7, 9, 10]]

我需要弄清楚如何操縱它來創建嵌套列表的可能組合的列表。 這些組合不能具有共享號碼的列表。 這是結果示例的一個示例:

network_1=[[1,2,3],[7,9,10]]
network_2=[[1,4,5],[7,9,10]]
network_3=[[1,3,6],[7,9,10]]

注意:1.此代碼將鏈接到一個不斷更新的csv文件,因此org_network列表中將包含不同數量的元素(這也意味着將有許多結果網絡。

我已經為此工作了大約四個小時,但尚未弄清楚。 任何幫助將不勝感激。 我主要是試圖使用循環和any()函數都沒有用。 謝謝你的幫助。

您可以將itertools.combinations()與設置交集一起使用:

>>> from itertools import combinations
>>> org_network=[[1, 2, 3], [1, 4, 5], [1, 3, 6], [7, 9, 10]]
>>> [[x, y] for x, y in combinations(org_network, r=2) if not set(x).intersection(y)]
[[[1, 2, 3], [7, 9, 10]], [[1, 4, 5], [7, 9, 10]], [[1, 3, 6], [7, 9, 10]]]

如果唯一元素的數量相對於集合的數量少,則這是一種有效的方法。

腳步:

  1. 對於每個唯一元素,存儲其中不會出現該元素的所有集合的索引。
  2. 對於網絡中的每個集合s ,使用第一步中的數據查找包含s每個元素的所有其他集合。
  3. 對對進行迭代,根據ID順序丟棄重復項。

from functools import reduce

org_network = [[1, 2, 3], [1, 4, 5], [1, 3, 6], [7, 9, 10]]

# convert to sets
sets = [set(lst) for lst in org_network]

# all unique numbers
uniqs = set().union(*sets)

# map each unique number to sets that do not contain it:
other = {x: {i for i, s in enumerate(sets) if x not in s} for x in uniqs}

# iterate over sets:
for i, s in enumerate(sets):
    # find all sets not overlapping with i
    no_overlap = reduce(lambda l, r: l.intersection(r), (other[x] for x in s))

    # iterate over non-overlapping sets
    for j in no_overlap:
        # discard duplicates
        if j <= i:
            continue

        print([org_network[i], org_network[j]])


# result
# [[1, 2, 3], [7, 9, 10]]
# [[1, 4, 5], [7, 9, 10]]
# [[1, 3, 6], [7, 9, 10]]

編輯:如果需要大於兩個的大小組合,則可以修改上述方法。 這是一個使用深度優先搜索來遍歷所有成對不相交組合的擴展。

def not_overlapping(set_ids):
    candidates = reduce(
        lambda l, r: l.intersection(r), (other[x] for sid in set_ids for x in sets[sid])
    )
    mid = max(set_ids)
    return {c for c in candidates if c > mid}


# this will produce "combinations" consisting of a single element
def iter_combinations():
    combs = [[i] for i in range(len(sets))]
    while combs:
        comb = combs.pop()
        extension = not_overlapping(comb)
        combs.extend(comb + [e] for e in extension)
        yield [org_network[i] for i in comb]


def iter_combinations_long():
    for comb in iter_combinations():
        if len(comb) > 1:
            yield comb


all_combs = list(iter_combinations_long())

暫無
暫無

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

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