Nor*_*ldt 1 python rss python-2.7
找到关于如何检查字符串列表是否在一行内的这个很好的答案如何检查 一行是否有列表中的一个字符串?
但是尝试用dict中的键做类似的事情似乎并不适合我:
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)
Run Code Online (Sandbox Code Playgroud)
输出:
['SEK', 'DKK']
<code>DKK</code>
<code>SEK</code>
testCounter is 377 and should be 2 - if not debug the code
Run Code Online (Sandbox Code Playgroud)
想想也许我的问题是因为.keys()给了我一个数组而不是列表..但还没弄明白如何转换它..
更改:
any(countryCode in line for countryCode in currencies.keys())
Run Code Online (Sandbox Code Playgroud)
至:
any([countryCode in line for countryCode in currencies.keys()])
Run Code Online (Sandbox Code Playgroud)
您的原始代码使用生成器表达式,而(我认为)您的意图是列表理解.请参阅:生成器表达式与列表理解
更新:我发现使用带有pylab导入的ipython解释器我得到了与你相同的结果(377计数与预期的2计数).我意识到问题是'any'来自numpy包,它意味着在数组上工作.接下来,我加载了一个没有pylab的ipython解释器,因此'any'来自内置.在这种情况下,您的原始代码有效.所以如果你使用ipython解释器类型:
help(any)
Run Code Online (Sandbox Code Playgroud)
并确保它来自内置模块.如果是这样,您的原始代码应该正常工作
| 归档时间: |
|
| 查看次数: |
796 次 |
| 最近记录: |