python - 而不是重复一个循环多次 'merge' 变成一个

标签 python loops for-loop

设置

我正在使用 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/

相关文章:

python - 运行命令并像在终端中一样近乎实时地分别获取其标准输出、标准错误

python - secret 圣诞老人分院帽

java - 尝试将 2 个数组传递给方法并使用这 2 个数组中的值打印出一个表

javascript - MapBox GLJS - 使用 for 循环创建标记时不显示

python - 遍历列表,每当出现特定类别的号码时,创建其他类别中最新号码的列表

使用 for 循环的 JavaScript 倒计时

python - 如何使用 Python 根据两个列表之一的列表元素出现来连接两个列表

python - sys.getsizeof 的深层版本

python - 如何在 Python 3 中像在 Python 2 中一样将 chr(0xdfff) 转换为 utf-8 字节?

javascript - 循环遍历对象数组并返回这些对象的累积数据