[英]How to group pairs in a list based on share items and connections in python
[英]Python: group a list basing on pairs of items
我的程序生成如下列表:
mydata = ["foo", "bar", "baz", "quux", "quid", "quo"]
從其他數據中我知道,這些可以成對分組(這里是元組列表,但可以更改為任何形式):
static_mapping = [("foo", "quo"), ("baz", "quux"), ("quid", "bar")]
夫妻倆沒有訂餐。
現在開始解決問題:我的程序生成mydata
,我需要將數據分組,但是要保留不匹配項的單獨列表。 原因是,在任何時候, mydata
可能都不會包含夫婦中的所有項目。
此類假設功能的預期結果:
mydata = ["foo", "bar", "quo", "baz"]
couples, remainder = group_and_split(mydata, static_mapping)
print(couples)
[("foo", "quo")]
print(remainder)
["bar", "baz"]
編輯:我嘗試過的示例(但他們停止尋找耦合):
found_pairs = list()
for coupling in static_mapping:
pairs = set(mydata).intersect(set(coupling))
if not pairs or len(pairs) != 2:
continue
found_pairs.append(pairs)
我被困在尋找一種可靠的方式來發出提醒。
您可以嘗試以下方法:
import copy
def group_and_split(mydata, static_mapping):
remainder = copy.deepcopy(mydata)
couples = []
for couple in static_mapping:
if couple[0] in mydata and couple[1] in mydata:
remainder.remove(couple[0])
remainder.remove(couple[1])
couples.append(couple)
return [couples, remainder]
如果值很大,Set可以讓您更快地運行,但是會占用內存,並且Deepcopy會保持原始數據完整。
假設功能的實現之一可能是:
from copy import deepcopy
def group_and_split(mydata, static_mapping):
temp = set(mydata)
couples = []
remainder = deepcopy(mydata)
for value1,value2 in static_mapping:
if value1 in temp and value2 in temp:
couples.append((value1,value2))
remainder.remove(value1)
remainder.remove(value2)
return couples, remainder
在這里,您將如何使用symmetric_difference
函數對sets
進行操作:
>>> full = ["foo", "quo", "baz", "quux", "quid", "bar", 'newone', 'anotherone']
>>> couples = [("foo", "quo"), ("baz", "quux"), ("quid", "bar")]
## now for the remainder. Note you have to flatten your couples:
>>> set(full).symmetric_difference([item for sublist in couples for item in sublist])
set(['anotherone', 'newone'])
>>>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.