【问题标题】:How to assign item from list to variable如何将列表中的项目分配给变量
【发布时间】:2020-10-08 20:30:18
【问题描述】:

我有以下输出:

datos=['Venta Casas CARRETERA NACIONAL, Nuevo León', 'Publicado el 29 de Abr', 'ABEDUL DE LADERAS', '3 Recámaras', '4.5 Baños', '300m² de Construcción', '300m² de Terreno', '2 Plantas', ' 81-1255-3166', ' Preguntale al vendedor', 'http://zuhausebienesraices.nocnok.com/', "INFOSTATS_ADOAnuncios('5', '30559440');"] 

如果每个项目在列表中,我想为每个项目分配一个不同的变量,否则它将为 0。例如:

recamara= the string from the list that has the word "Recámara"
bano= the string from the list that has the string "Baño"

等等。如果“Baño”这个词不在列表中,那么bano= 0

【问题讨论】:

  • tag 一种编程语言,以便合适的人找到您的问题。
  • 重要的是要提到变量在列表中的位置并不总是相同。

标签: python list iteration assign items


【解决方案1】:

如果您使用的是 Python,则可以使用列表推导来执行此操作。

datos = ['Venta Casas CARRETERA NACIONAL, Nuevo León', 'Publicado el 29 de Abr', 'ABEDUL DE LADERAS', '3 Recámaras', '4.5 Baños', '300m² de Construcción', '300m² de Terreno', '2 Plantas', ' 81-1255-3166', ' Preguntale al vendedor', 'http://zuhausebienesraices.nocnok.com/', "INFOSTATS_ADOAnuncios('5', '30559440');"]

# list of strings which has "Casas" in it
casas_list = [string for string in datos if "Casas" in string]

print(casas_list)

print(len(casas_list))

【讨论】:

    【解决方案2】:
    recamara = [s for s in datos if "Recámara" in s]
    bano = [s for s in datos if "Baño" in s]
    
    if len(recamara)==0:
        recamara = 0
    else:
        print(recamara[0]) #print the entire list if there will be more than 1 string
    
    if len(bano)==0:
        bano = 0
    else:
        print(bano[0])
    

    【讨论】:

      猜你喜欢
      • 2016-02-10
      • 2015-05-31
      • 2018-08-23
      • 2018-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多