List 向列表中添加for循环元素

List 向列表中添加for循环元素,list,python-2.7,for-loop,List,Python 2.7,For Loop,我正在编写一个代码,它从一个站点获取一些文本,然后通过for循环获取我感兴趣的部分文本。我可以打印此文本,但我想知道如何将其发送到列表供以后使用。到目前为止,我写的代码就是这个 import urllib2 keyword = raw_input('keyword: ') URL = "http://www.uniprot.org/uniprot/?sort=score&desc=&compress=no&query=%s&fil=&limit=10&

我正在编写一个代码,它从一个站点获取一些文本,然后通过for循环获取我感兴趣的部分文本。我可以打印此文本,但我想知道如何将其发送到列表供以后使用。到目前为止,我写的代码就是这个

import urllib2

keyword = raw_input('keyword: ')

URL = "http://www.uniprot.org/uniprot/?sort=score&desc=&compress=no&query=%s&fil=&limit=10&force=no&preview=true&format=fasta" % keyword

filehandle = urllib2.urlopen(URL)

url_text = filehandle.readlines()

for line in url_text:
    if line.startswith('>'):
        print line[line.index(' ') : line.index('OS')]

只需使用
append

lines = []
for line in url_text:
    if line.startswith('>'):
        lines.append(line) # or whatever else you wanted to add to the list
        print line[line.index(' ') : line.index('OS')]

编辑:另一方面,python可以直接在文件上进行for循环,如下所示:

url_text = filehandle.readlines()
for line in url_text:
    pass

# can be shortened to:
for line in filehandle:
    pass

只需使用
append

lines = []
for line in url_text:
    if line.startswith('>'):
        lines.append(line) # or whatever else you wanted to add to the list
        print line[line.index(' ') : line.index('OS')]

编辑:另一方面,python可以直接在文件上进行for循环,如下所示:

url_text = filehandle.readlines()
for line in url_text:
    pass

# can be shortened to:
for line in filehandle:
    pass

这是一个很好的方法,但是有了它,我就不会附加整行了吗?如最后一行命令所示,我只想在第一个空格和“OS”之间的那一行中添加文本。@NunoChicória是的,但您可以在列表中添加您喜欢的内容。如果您只想保留以前打印的内容,可以执行
lines.append(line[line.index(“”):line.index('OS'))
这是一种很好的方法,但这样我就不会追加整行了吗?如最后一行命令所示,我只想在第一个空格和“OS”之间的那一行中添加文本。@NunoChicória是的,但您可以在列表中添加您喜欢的内容。如果您只想保留以前打印的内容,可以执行
line.append(line[line.index(“”):line.index('OS'))