简体   繁体   中英

python create list within while loop

I have defined a function to read lines from a file into a list. I then want to call this function from within a while loop. The list is created correctly on the first loop, but the following loops create an empty list.

How can I get my code to regenerate the list each time? (For clarification, this is not the final function, but I have isolated the issue in my code to the generation of the list).

def get_random_gene_list(input):
    disease_genes = []
    for line in input:
        disease_genes.append(line.strip())

    return disease_genes

x=0
while x < 5:

    unpack_gene_list = get_random_gene_list(args.i)
    print unpack_gene_list


    x = x + 1

Presuming that args.i is a file object, you're reading the file on the first loop, which puts the file pointer at the end of the file. Do you need to re-read the file every loop? If not, you should call the function once outside the while loop and save the resulting list. In fact, you don't even need the function. Also, you should use a for loop in this case.

unpack_gene_list = list(args.i)

x = 0
for x in range(5):
    print unpack_gene_list

This works fine for me, unless I misunderstood your question. Problem might lie in your input.

k = ['1','1','a','aa']

def get_random_gene_list(input):
    disease_genes = []
    for line in input:
        disease_genes.append(line.strip())
    return disease_genes

x=0
while x < 5:
    unpack_gene_list = get_random_gene_list(k)
    print unpack_gene_list
    x = x + 1

Output:

['1', '1', 'a', 'aa']
['1', '1', 'a', 'aa']
['1', '1', 'a', 'aa']
['1', '1', 'a', 'aa']
['1', '1', 'a', 'aa']

Process finished with exit code 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM