Home > database >  how do i select the first value of "for" loop within the for loop?
how do i select the first value of "for" loop within the for loop?

Time:05-23

I used following code to descending the degree value of a network, using networkx. Now I want to select only the fist value of the iteration whithin the same for loop. code as follows:

for i in sorted(G.degree, key=lambda x: x[1], reverse=True):
    list_id=(i[0])
    print(list_id)

Output gives as follows:

264
32
19
4
101
15

Could you please tell me a way to select only the first value of this iteration, (i.e., 264)

CodePudding user response:

It looks like you only want the max? Then no need to sort as this is more expensive than max.

list_id = max(G.degree, key=lambda x: x[1])

CodePudding user response:

use this :

for i in sorted(G.degree, key=lambda x: x[1], reverse=True):
    list_id=(i[0])
    break # add this line
    print(list_id)

CodePudding user response:

my_list = [264, 32, 19, 4, 101, 15]
print(sorted(my_list).pop())

CodePudding user response:

Instead of printing the values, you could store them, for example into a list, so you can use them as needed:

list_ids = []
for i in sorted(G.degree, key=lambda x: x[1], reverse=True):
    list_id=(i[0])
    list_ids.append(list_id)

list_ids[0]
  • Related