你看起來像一個圖的邊緣列表,你想要找出的是他們是否連接(即他們有一個共同的邊緣)。
您還有一個有向圖,邊的順序爲您的「匹配」計數(這與您定義的不一致)。
edge = [['a','b'],
['b','c'],
['c','a'],
['d','a'],
['e',None]]
# order of edges doesn't count
def is_connected(e1, e2):
return e1[0] == e2[1] or e1[1] == e2[0]
# order of edges counts
def is_child(e1, e2):
return e1[1] == e2[0]
你想要的是第二檢查is_child
,我認爲
print(is_connected(edge[0],edge[1]))
print(is_connected(edge[1],edge[2]))
print(is_connected(edge[0],edge[2]))
print(is_child(edge[0],edge[1]))
print(is_child(edge[1],edge[2]))
print(is_child(edge[0],edge[2])) # false
print(is_child(edge[2],edge[0]))
如果您想通過第二座標,以檢查此類型圖中的所有邊面向連接的,你基本上要組並且在熊貓中有一個方便的功能groupby
可以做到這一點:
import pandas as pd
df = pd.DataFrame(edge)
grouped = df.groupby(1)
grouped.groups
# Output:
{'a': [2L, 3L], 'c': [1L], 'b': [0L]}
grouped.groups['a']
# Output:
# [2L, 3L]
grouped[0].apply(lambda x: ','.join(x)).reset_index()
# Output:
# 1 0
# 0 a c,d
# 1 b a
# 2 c b
第一個元素是唯一的嗎?如果他們不是,應該發生什麼,例如在第一個位置出現兩行「a」? –
@MartijnPieters他們是獨一無二的。忘了提到這一點。 – Thomasedv
列表是否可以包含內容['a','a']? – Moberg