Frage

The following code:

for j in reversed(range(0,15)):
  print i
  successors = g.successors(totuple(total_nodes[j,:]))
  array = [0,0,0,0]
  a=0
  i = i+1

  for succ in successors:
    print g.node[succ]
    array[a]=g.node[succ]
    a+=1      

    print array
    print sum(item['key'] for item in array)

produces the following output:

 1
 {'key': 0.0}
 {'key': 0.39730768970355257}
 {}
 {'key': 0.0}

 [{'key': 0.0}, {'key': 0.39730768970355257}, {}, {'key': 0.0}]
  1. I don't get why some nodes don't have keys {}. But suppose I want to disregard those.
  2. I want to sum those values or 'keys'

So based on other questions I tried:

  1. print sum(item['key'] for item in array) produces:

    KeyError: 'key'

  2. print sum([i for i in array.values()]) produces:

    AttributeError: 'list' object has no attribute 'values'

War es hilfreich?

Lösung

Try changing the last line to this in order to avoid key errors:

sum(item['key'] for item in array if 'key' in item)

Andere Tipps

you can use sum(item.get('key', 0)) for item in array) which would return 0 if key is not found

Some of your nodes are lists or integers -- which is why, not being dicts, they don't have a values() method and can't be indexed with string keys.

As for why your data is structured so, we can't tell you unless you give us more context (like, what's g? What does successors() do? totuple()? What is the actual problem you're attempting to solve?).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top