意外的列表出现在 Python 循环中

2024-04-30 05:10:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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" 

本质上,“search”列表是我要在一些分子中匹配的两个字符串,我想使用pybel软件迭代allmol中包含的每个分子中的两个字符串。然而,我得到的结果是:

^{pr2}$

正如预期的那样,除了一些额外的空名单,在这些名单上我搞砸了,我看不出他们是从哪里来的。它们出现在“\n”之后,因此不是聪明的芬德尔(). 我做错什么了? 谢谢你的帮助。在


Tags: 字符串inimport列表forsearch分子print
2条回答

allmol有2个项,因此您将循环两次,matches第二次是空列表。在

请注意,换行符是如何在每一行之后打印的;将"\n"更改为{}可能会为您清理干净:

print matches, "<  matches"
# or, more commonly:
print "matches:", matches

也许应该是这样结束的

for b in allmol:  
    matches.append(smarts.findall(b))  
print matches, "\n"

否则我不知道你为什么要初始化匹配到一个空列表

如果是这样的话,你可以改为写

^{pr2}$

另一种可能是文件以空行结尾

for b in allmol:  
    if not b.strip(): continue
    matches.append(smarts.findall(b))  
    print matches, "\n"

相关问题 更多 >