我是python的新手,我有以下一段带有嵌套循环的测试代码,并且我得到了一些意外的列表:
import pybel
import math
import openbabel
search = ["CCC","CCCC"]
matches = []
#n = 0
#b = 0
print search
for n in search:
print "n=",n
smarts = pybel.Smarts(n)
allmol = [mol for mol in pybel.readfile("sdf", "zincsdf2mols.sdf.txt")]
for b in allmol:
matches = smarts.findall(b)
print matches, "\n" 本质上,“搜索”列表是我在一些分子中寻找匹配的几个字符串,我想使用pybel软件迭代allmol中包含的每个分子中的这两个字符串。然而,我得到的结果是:
['CCC', 'CCCC']
n= CCC
[(1, 2, 28), (1, 2, 4), (2, 4, 5), (4, 2, 28)]
[]
n= CCCC
[(1, 2, 4, 5), (5, 4, 2, 28)]
[] 正如预期的那样,除了几个额外的空列表之外,它们把我搞得乱七八糟,我看不出它们是从哪里来的。它们出现在"\n“之后,因此不是smarts.findall()的伪像。我做错了什么?谢谢你的帮助。
发布于 2010-02-15 03:59:00
allmol有两个项目,所以你循环了两次,第二次matches是一个空列表。
请注意每行之后是如何打印的;将该"\n"更改为"<-- matches"可能会为您理清思路:
print matches, "<-- matches"
# or, more commonly:
print "matches:", matches发布于 2010-02-15 04:53:45
也许它应该是这样结束的
for b in allmol:
matches.append(smarts.findall(b))
print matches, "\n"否则我不知道你为什么要把匹配项初始化为空列表
如果是这样的话,您可以改写
matches = [smarts.findall(b) for b in allmol]
print matches另一种可能是文件以空行结束
for b in allmol:
if not b.strip(): continue
matches.append(smarts.findall(b))
print matches, "\n"https://stackoverflow.com/questions/2262509
复制相似问题