簡體   English   中英

如何使用現有的元組列表創建新的元組列表

[英]How to create a new list of tuples with existing list of tuples

我有一個這樣的元組列表 -

list1 = [('alpha', 'beta'),
         ('beta','gama')
         ('alpha','lamda')
         ('gama', 'lamda'),
         ('euphor', 'tuphor')]

我想根據以下邏輯制作一個新列表 -

對於原始列表中不存在的每一對都將包含在新列表中,如下所示:

new_list = [('alpha','gama'),
            (alpha, tuphor),
            (alpha, euphor),
            (beta,lamda),
            ()...]

同樣地。

誰能建議在 python 中這樣做的方法?

謝謝。

這是使用itertools和集合的解決方案:

list1 = [('alpha', 'beta'),
         ('beta','gama'), 
         ('alpha','lamda'), 
         ('gama', 'lamda'),
         ('euphor', 'tuphor')]

all_items = set(itertools.chain(*list1))

all_pairs = set(itertools.product(all_items, all_items))
new_pairs = all_pairs.difference(list1)

結果( new_pairs )是:

{('alpha', 'alpha'),
 ('alpha', 'euphor'),
 ('alpha', 'gama'),
 ('alpha', 'tuphor'),
 ('beta', 'alpha'),
 ('beta', 'beta'),
 ('beta', 'euphor'),
 ('beta', 'lamda'),
 ('beta', 'tuphor'),
 ...
from itertools import combinations

list1 = [('alpha', 'beta'),
         ('beta','gama'),
         ('alpha','lamda'),
         ('gama', 'lamda'),
         ('euphor', 'tuphor')]

elements = list(set([e for l in list1 for e in l])) # find all unique elements

complete_list = list(combinations(elements, 2)) # generate all possible combinations

#convert to sets to negate the order

set1 = [set(l) for l in list1]
complete_set = [set(l) for l in complete_list]

# find sets in `complete_set` but not in `set1`
ans = [list(l) for l in complete_set if l not in set1]

Output:

[['euphor', 'lamda'],
 ['euphor', 'gama'],
 ['euphor', 'beta'],
 ['euphor', 'alpha'],
 ['lamda', 'beta'],
 ['lamda', 'tuphor'],
 ['gama', 'alpha'],
 ['gama', 'tuphor'],
 ['beta', 'tuphor'],
 ['tuphor', 'alpha']]

您可以

  • 收集不同的物品
  • 計算所有排列
  • 獲取所有組合與現有組合之間的差異
list1 = [('alpha', 'beta'), ('beta', 'gama'), ('alpha', 'lamda'), ('gama', 'lamda'), ('euphor', 'tuphor')]
from itertools import chain, combinations

items = set(chain(*list1))  # {'euphor', 'gama', 'tuphor', 'beta', 'lamda', 'alpha'}

all_perm = set(combinations(items, r=2))
new_perm = all_perm - set(list1)

print(len(all_perm), all_perm)  # 30
print(len(new_perm), new_perm)  # 25

您只需要獲取原始列表中的唯一名稱,然后應用if條件。 試試這個,如果您遇到任何問題,請告訴我。

new_list = []
names = set(np.array(list1).ravel())
for i in names:
    for j in names:
        if i!=j:
            if ((i,j) not in list1) & ((j,i) not in list1) & ((i,j) not in new_list) & ((j,i) not in new_list):
                new_list.append((i,j))

暫無
暫無

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

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