Python 3:如何删除python列表中的奇数

时间:2019-02-03 08:47:04

标签: python python-3.x list tuples

下面是供参考的示例:

pairlist = [("A","B"),("Q","R"),("S","T"),("C","E"),("F","G"),("G","I"),("A","Y"),("B","C"),("B","D")]

我需要从此列表中获取更多相互关联的元组(直接或间接)值

例如: 请参考下面的列表,其中在pairlist [0]位置的元组(“ A”,“ B”)中,“ A”与“ B”链接,而pairlist [7]中的“ B”与“ C”链接,依此类推它大量地间接互连,因为“ G”之间的互连较少。

pairs1 = ["A", "B", "C", "D", "E", "Y"] #More Interconnected indirectly

pairs2 = ["G", "F", "I"] #Less Interconnected indirectly

列表No中与任何一个互连的下面的元组。

("Q","R"),("S","T")

即使“ G”是重复的,并且一次也没有与主语互连,但它与其他元素分开互连,而与其他元素的连接很少。

如何获取以下列表

pairs = ["A", "B", "C", "D", "E", "Y"]

1 个答案:

答案 0 :(得分:3)

您可以使用软件包networkx

import networkx as nx

pairlist = [("A","B"),("C","E"),("F","G"),("G","I"),("A","Y"),("B","C"),("B","D")]

G = nx.Graph()
G.add_edges_from(pairlist)
for i in nx.connected_components(G):
    print(i)
# {'B', 'C', 'E', 'D', 'Y', 'A'}
# {'I', 'F', 'G'}

Graph

要绘制图形,请使用:

import matplotlib.pyplot as plt

nx.draw(G, with_labels=True)
plt.show()

或者如果您使用jupyter笔记本:

%matplotlib inline
nx.draw(G, with_labels=True)