简体   繁体   English

Python在while循环中创建列表

[英]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. 然后,我想在while循环内调用此函数。 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. 假定args.i是文件对象,则在第一个循环中读取文件,该循环将文件指针放在文件末尾。 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. 如果没有,则应在while循环外调用一次该函数并保存结果列表。 In fact, you don't even need the function. 实际上,您甚至不需要此功能。 Also, you should use a for loop in this case. 另外,在这种情况下,您应该使用for循环。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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