找到关于如何检查字符串列表是否在一行内的好答案 How to check if a line has one of the strings in a list?
但是尝试用字典中的键做类似的事情对我来说似乎并不适合我:
import urllib2
url_info = urllib2.urlopen('http://rss.timegenie.com/forex.xml')
currencies = {"DKK": [], "SEK": []}
print currencies.keys()
testCounter = 0
for line in url_info:
if any(countryCode in line for countryCode in currencies.keys()):
testCounter += 1
if "DKK" in line or "SEK" in line:
print line
print "testCounter is %i and should be 2 - if not debug the code" % (testCounter)
输出:
['SEK', 'DKK']
<code>DKK</code>
<code>SEK</code>
testCounter is 377 and should be 2 - if not debug the code
认为我的问题可能是因为 .keys() 给我一个数组而不是一个列表。但还没有想出如何转换它。 .
请您参考如下方法:
改变:
any(countryCode in line for countryCode in currencies.keys())
到:
any([countryCode in line for countryCode in currencies.keys()])
您的原始代码使用生成器表达式,而(我认为)您的意图是列表理解。 参见:Generator Expressions vs. List Comprehension
更新: 我发现使用导入了 pylab 的 ipython 解释器得到了与您相同的结果(377 计数与预期的 2)。我意识到问题是“任何”来自 numpy 包,它意味着在数组上工作。 接下来,我加载了一个没有 pylab 的 ipython 解释器,这样“任何”都来自内置。在这种情况下,您的原始代码有效。 因此,如果您使用 ipython 解释器类型:
help(any)
并确保它来自内置模块。如果是这样,您的原始代码应该可以正常工作。
