我有一个列表source
,该列表代表网络图中的节点。我遍历source
中的节点以获得相邻节点的子列表。同时,将所有相邻节点与另一个列表watch_list
进行比较。
我想创建一个单独的列表adjacent
,该列表指定source
中的节点在watch_list
中是否具有邻居。请参见下面的代码:
import networkx as nx
import pandas as pd
source = ['A','C','B','D','G','C','B','G']
target = ['B','T','G','A','T','B','H','V']
weight = [2, 1, 6, 6, 3, 3, 2, 1]
watch_list = ['H','D','T']
df = pd.DataFrame([source,target,weight])
df = df.transpose()
df.columns = ['source','target','weight']
G = nx.from_pandas_edgelist(df,'source','target','weight')
adjacent = []
for i in source:
for j in list(nx.all_neighbors(G, i)):
if j in watch_list:
adjacent.append('Y')
else: adjacent.append('N')
print(adjacent)
运行此代码将返回以下列表:
>>> ['N', 'Y', 'Y', 'N', 'N', 'N', 'N', 'Y', 'N', 'N', 'Y', 'N', 'Y', 'N', 'N', 'N', 'N', 'Y', 'N', 'Y', 'N']
问题在于代码正在遍历所有邻居,并在每次迭代后附加“ Y”或“ N”。
如何控制流仅将'Y'或'N'附加一次,以指示source
中的节点在watch_list
('Y')上具有邻居,或者没有't('N')。
这似乎是一个简单的流程控制问题,但我似乎无法正确解决。 任何建议表示赞赏!
答案 0 :(得分:1)
此代码为每个'Y'
产生一个'N'
或j
:
for j in list(nx.all_neighbors(G, i)):
if j in watch_list:
adjacent.append('Y')
else: adjacent.append('N')
如果您只想知道是否有邻居的j
,请使用any
:
is_there_any = any(j in watch_list
for j in list(nx.all_neighbors(G, i)))
if is_there_any:
adjacent.append('Y')
else:
adjacent.append('N')
或者,我宁愿简单地做到这一点:
adjacent = [any(j in watch_list
for j in list(nx.all_neighbors(G, i)))
for i in source]
# adjacent now holds booleans, rather than strings, but I think that is better
答案 1 :(得分:1)
您可以使用any()
并检查您的watch_list
中是否有邻居:
adjacent = []
for i in source:
if any(x in watch_list for x in list(nx.all_neighbors(G, i))):
adjacent.append('Y')
else:
adjacent.append('N')
print(adjacent)
结果:
['Y', 'Y', 'Y', 'N', 'Y', 'Y', 'Y', 'Y']