Turning a list into variables in python

This question already has an answer here:

  • In Python, how do I read a file line-by-line into a list? 35 answers

  • Use a context manager:

    with open(myfile, 'r') as f:
        for line in f:
            print(line)
    

    Not sure how your file is formatted, but if it is in the form of:

    Question
    Answer
    Question
    Answer
    .
    .
    .
    Question N
    Answer N
    

    You can call enumerate() over a generator within the context manager and go to specific lines. For example, if you know the line number or perhaps build a dictionary of Q&A for even lines:

    with open(myfile, 'r') as f:
        q_a = {}
        for num, line in enumerate(line for line in f):
            if num % 2 = 0:
                question = line
            else:
                q_a[question] = line
    
    链接地址: http://www.djcxy.com/p/42366.html

    上一篇: 在POSIX系统上修改多个文件的安全且有效的方法?

    下一篇: 在python中将列表变成变量