【问题标题】:Python looping through listsPython循环遍历列表
【发布时间】:2019-04-15 18:25:20
【问题描述】:

我有一个名为:

word_list_pet_image = [['beagle', '01125.jpg'], ['saint', 'bernard', '08010.jpg']]

此列表中有更多数据,但我保持简短。我正在尝试遍历此列表并检查该单词是否仅是字母字符,如果这是真的,将该单词附加到一个名为

的新列表中
pet_labels = []

到目前为止我有:

word_list_pet_image = []
for word in low_pet_image:
    word_list_pet_image.append(word.split("_"))

for word in word_list_pet_image:
    if word.isalpha():
        pet_labels.append(word)
        print(pet_labels)

例如,我试图将单词beagle 放入列表pet_labels,但跳过01125.jpg。见下文。

pet_labels = ['beagles', 'Saint Bernard']

我收到一个属性错误

AtributeError: 'list' 对象没有属性 'isalpha'

我确信这与我没有正确地遍历列表有关。

【问题讨论】:

    标签: python list loops for-loop


    【解决方案1】:

    您似乎正在尝试在每个子列表中加入字母单词。列表推导在这里会很有效。

    word_list = [['beagle', '01125.jpg'], ['saint', 'bernard', '08010.jpg']]
    
    pet_labels = [' '.join(w for w in l if w.isalpha()) for l in word_list]
    
    >>> ['beagle', 'saint bernard']
    

    【讨论】:

    • 我不知道列表理解会阅读此内容。谢谢。
    【解决方案2】:

    你有列表的列表,所以蛮力方法是嵌套循环。喜欢:

    for pair in word_list_pet_image:
        for word in pair:
            if word.isalpha():
                #append to list
    

    另一个选项可能是单个 for 循环,但随后对其进行切片:

    for word in word_list_pet_image:
        if word[0].isalpha():
            #append to list
    

    【讨论】:

      【解决方案3】:
      word_list = [['beagle', '01125.jpg'], ['saint', 'bernard', '08010.jpg']]
      

      为什么不list comprehension(仅当非全字母元素总是在最后时):

      pet_labels = [' '.join(l[:-1]) for l in word_list]
      

      【讨论】:

        【解决方案4】:
        word_list_pet_image.append(word.split("_"))
        

        .split() 返回列表,因此word_list_pet_image 本身包含列表,而不是简单的单词。

        【讨论】:

          猜你喜欢
          • 2018-10-26
          • 1970-01-01
          • 1970-01-01
          • 2014-06-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多