Python字典-值 [英] Python dictionary - value
问题描述
我有一个if
block 语句,该语句正在检查我分配给变量movieTitle
的字符串是否包含预定义词典中的键值对值.
I have an if
block statement that is checking if a string that I have assigned to variable movieTitle
contains the value of a key-value pair in a predefined dictionary.
我的代码是:
import mechanize
from bs4 import BeautifulSoup
leaveOut = {
'a':'cat',
'b':'dog',
'c':'werewolf',
'd':'vampire',
'e':'nightmare'
}
br = mechanize.Browser()
r = br.open("http://<a_website_containing_a_list_of_movie_titles/")
html = r.read()
soup = BeautifulSoup(html)
table = soup.find_all('table')[0]
for row in table.find_all('tr'):
# Find all table data
for data in row.find_all('td'):
code_handling_the_assignment_of_movie_title_to_var_movieTitle
if any(movieTitle.find(leaveOut[c]) < 1 for c in 'abcde'):
do_this_set_of_instructions
else:
pass
我的想法是,可以使用.find()
方法测试字符串movieTitle
中字典的任何值(预定义),如果找到该值,则将返回索引整数值.大于(或至少)等于1.因此,如果条件的结果小于< 1(不存在时通常为-1),则我可以继续执行程序的其余部分,否则不执行程序的其余部分.罢工>
My thoughts are that I can test the string movieTitle
for any of the values of the dictionary (predefined) by using the .find()
method, which if the value is found will return an index integer value of greater than (or at least) equal to 1. Therefore if the result of the condition is <1 (usually -1 when absent) I can continue with the rest of the program, otherwise not perform the rest of the program.
但是,当我使用Aptana调试功能时,我可以看到该 if
块上的断点从未处于激活状态,就像Aptana正在跳过它.为什么会这样?
However, when I use the Aptana debug feature I can see that my breakpoint on this if
block are never engaged, as if Aptana is skipping right over it. Why is this?
为清楚起见,已包含更多代码.在查看了建议之后,我使用了@kqr建议的代码.但是,尽管leavesOut dict中包含字符串值,但我的实际程序仍显示movieTitle.为什么?
Have included more code for clarity. Having reviewed the suggestions I have used the code that @kqr suggested. However, my actual program still displays movieTitle despite having string values contained in leaveOut dict. Why?
推荐答案
您能在此确认您要实现的目标吗?如果movieTitle中不存在leaveOut
词典中的任何值,您正在尝试执行一组指令.如果是这样:
Could you confirm exactly what you're trying to achieve here? You're trying to execute a set of instructions if ANY of the values in the leaveOut
dictionary is NOT present in the movieTitle? If so:
if [x for x in leaveOut.values() if x not in movieTitle]:
会更加简洁.另外,如果您要使用上面的公式,则比较器必须为0
而不是1
,否则第一个字符的匹配项将触发指令集.
would be more concise. Also, if you're going to use the formulation above then the comparator has to be 0
rather than 1
otherwise matches at the first character will fire the set of instructions.
这篇关于Python字典-值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!