我用 networkx 创建了一个图,每个节点都有一些属性。所以我想搜索所有节点的特定属性,并将每个具有此属性的节点保存在列表中。我编写了以下代码,但出现错误:
for node in G.nodes():
for attribute in G.node[node]['attributes']:
if attribute in question:
setOfUsers.append(node)
Run Code Online (Sandbox Code Playgroud)
使用此代码,我收到以下错误:
for attribute in G.node[node]['attributes']:
KeyError: 'attributes'
Run Code Online (Sandbox Code Playgroud)
所以我搜索了论坛,并尝试了一些不同的方法来解决问题:
for node, data in G.nodes(data=True):
if data['attributes'] == question[0]:
setOfUsers.append(node)
Run Code Online (Sandbox Code Playgroud)
但我有同样的错误。如何遍历属性?
更新:我使用下面的代码添加节点属性。我从文件中读取属性,拆分逗号和换行符,然后将列表保存在节点中
for line in file2:
line = line.strip()
words = line.split('\t')
node = int(words[0])
attributes= words[1]
splittedAttributes = attributes.split(',')
if node in G.nodes():
G.node[node]['attributes'] = splittedAttributes
Run Code Online (Sandbox Code Playgroud) 我有一个带有节点的字典:
supernodes = list(nx.connected_components(G1))
Run Code Online (Sandbox Code Playgroud)
结果print(supernodes)是:
[{1, 2, 3, 5}, {8, 6}, {7, 9, 10, 12, 13}, {4}, {11}, {14}, {15}]
Run Code Online (Sandbox Code Playgroud)
如何将每个列表合并到一个节点?我找到了这个函数,nx.contracted_nodes(G, (1, 3))但是我如何放置{1,2,3,5}, {8,6}等并创建 7 个签约节点?
我有n个数字和数字z.我想创建一个算法(伪代码)来查找在O(nlogn)中是否存在x + y = z的对(x,y).
我以为我可以运行quicksort算法.然后我将有2个数组:array1(元素<pivot)和array2(元素> pivot).如果数组中的第一个元素是<z,那么我可以检查array1中的所有其他元素以找到x + y = z的对.否则,如果array1中的第一个元素是> z,那么我将转到array2并执行相同的过程.我的建议是真的吗?
我有这样的数据集:
water, 5
eggs, 3
juice, 7
bread, 4
Run Code Online (Sandbox Code Playgroud)
我保存所有这些
HashMap<String, Integer> dataSet = new LinkedHashMap<String,Integer>();
Run Code Online (Sandbox Code Playgroud)
现在我想创建一个函数来打印从最大整数到最小的元素:
juice, 7
water, 5
bread, 4
eggs, 3
Run Code Online (Sandbox Code Playgroud)
我认为最简单的方法是创建一个HashMap数据集的副本,然后我必须运行HashMapCopy,找到最大值,打印最大元素并从列表中删除它.
private static void printMaxToMin(){
dataSetCopy = new LinkedHashMap<String,Integer>(dataSet);
}
Run Code Online (Sandbox Code Playgroud)
如何运行所有列表,找到最大值,每次打印具有最大值的元素对然后删除它?