设置
我正在使用 Scrapy 抓取公寓广告。对于某些住房特征,我循环遍历每个广告获得的列表 BC
的元素。如果该特征在列表中,我指定"is",如果不在列表中,则指定“否”。例如
for x in BC:
if 'Terraza' in x:
terrace = 'yes'
break
else:
terrace = 'no'
对于每个“是-否”特征,我都有上述循环的副本。
问题
除了遍历列表的元素之外,我还想遍历特征本身。 IE。我想将每个特征的所有循环“合并”为一个循环。
我尝试了以下(我的实际 bcl
确实包含多个元素):
found = False
bcl = ['Terraza']
for x in l: # l is a list of strings containing housing characteristics
for y in bcl:
if y in x:
y = 'yes'
found = True
break
else:
y = 'no'
if found:
break
terrace = Terrazza
但此循环不会创建变量 Terrazza
。我不确定我能用全局变量解决这个问题。
如何让这个循环工作?
最佳答案
根据想要的结果,您可以采用不同的方法。在这种情况下,我倾向于使用更实用的编码风格。我不确定这是否是您想要的,但我认为您可以这样做:
list_characteristics = ['Terraza', "Swimming pool"] # sample ad text - list of strings
bcl = ["test1", "test2", "Terraza", "test3"] # sample checklist - list of strings
def check_characteristics(checklist, adlist):
list_of_found_items = []
for characteristic in list_characteristics:
print("characteristic:", characteristic)
for item in bcl:
print("item:", item)
if item in characteristic:
list_of_found_items.append(item)
return list_of_found_items
result_list = check_characteristics(bcl, list_characteristics)
print("This ad has the following characteristics:", result_list)
使用上面的代码,您有一个函数,它接受两个字符串列表并列出找到的所有项目。如果您想知道是否至少有其中一个,您可以使用此其他功能作为一种更快的短路方式:
list_characteristics = ['Terraza', "Swimming pool"] # ad text - list of strings
bcl = ["test1", "test2", "Terraza", "test3"] # checklist - list of strings
def has_any_characteristic(checklist, adlist):
for characteristic in list_characteristics:
for item in bcl:
if item in characteristic:
return True
return False
result = has_any_characteristic(bcl, list_characteristics)
print("This ad has at least one of the wanted characteristics?", result)
似乎有很多代码,但您只需编写一次代码,然后在需要时随时使用,以简洁易读的方式,恕我直言。这两个函数的定义甚至可以放在一个单独的模块中,您可以在需要的地方导入。因此,在主代码中,您只需使用一行来调用该函数。每个函数都允许以一种易于理解的方式回答一个简单的问题,如上面两个代码示例中的 print()
语句所示。
关于python - 而不是重复一个循环多次 'merge' 变成一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43684643/