Home > Software design >  How to append elements to a list with a loop?
How to append elements to a list with a loop?

Time:10-01

import random

count = 1
attack_count = 0
Node_list = ['a','b','c','d','e']
a, b, c, d, e = 1,1,1,1,1
while True:
    value_list = random.sample(range(10, 100), 5) 
    a = value_list[0]
    b = value_list[1]
    c = value_list[2]
    d = value_list[3]
    e = value_list[4]

    print(count, "Round, Values : ", a, b, c, d, e)
    Biggest_N = max(a,b,c,d,e)
    index = value_list.index(Biggest_N) 
    print("Biggest Node:", Node_list[index]) 

    CH_list = []
    for i in range(count):
        CH_list.append(Node_list[index])
    print(CH_list)

    if count >= 10 :
        break
    count  = 1

first, thanks for your help I write this code by using Python. In this code, I want CH_list to append element that Biggest Node each count. for example, If Biggest Node is c in count 1, CH_list may print [c] If Biggest Node is b in count 2, CH_list may print [c, b] ....

but it's not working, in my code, If Biggest Node is b in count 2, CH_list print [b, b].

Can you tell me how to solve this problem?

CodePudding user response:

If what you want to do is accumulate the biggest node for each iteration in a list, you have to declare CH_list outside the while loop. That way the list is not reset every iteration.

Also, there is no need for the for loop, since all it does is add the same node count times to an empty list.

Here is the solution:

import random

count = 1
attack_count = 0
Node_list = ['a','b','c','d','e']
a, b, c, d, e = 1,1,1,1,1
CH_list = [] # Declare list outside loop
while True:
    value_list = random.sample(range(10, 100), 5) 
    a = value_list[0]
    b = value_list[1]
    c = value_list[2]
    d = value_list[3]
    e = value_list[4]

    print(count, "Round, Values : ", a, b, c, d, e)
    Biggest_N = max(a,b,c,d,e)
    index = value_list.index(Biggest_N) 
    print("Biggest Node:", Node_list[index]) 

    CH_list.append(Node_list[index]) # Append biggest node to the list
    print(CH_list)

    if count >= 10 :
        break
    count  = 1

CodePudding user response:

import random

count = 1
CH_list = []
attack_count = 0
Node_list = ['a','b','c','d','e']
a, b, c, d, e = 1,1,1,1,1
while True:
    value_list = random.sample(range(10, 100), 5) 
    a = value_list[0]
    b = value_list[1]
    c = value_list[2]
    d = value_list[3]
    e = value_list[4]

    print(count, "Round, Values : ", a, b, c, d, e)
    Biggest_N = max(a,b,c,d,e)
    index = value_list.index(Biggest_N) 
    print("Biggest Node:", Node_list[index]) 

    

    CH_list.append(Node_list[index])
    print(CH_list)
    
    if count >= 10 :
        break
    count  = 1
  • Related