【问题标题】:Removing all strings in a list that are of x length删除列表中长度为 x 的所有字符串
【发布时间】:2021-05-04 04:52:54
【问题描述】:

我的一个修订实践涉及创建一个函数,该函数删除列表中字符串长度最长的所有字符串。

预期输出:

words_list = ['fish', 'barrel', 'like', 'shooting', 'sand', 'bank']
print(remove_long_words(words_list))
['fish', 'barrel', 'like', 'sand', 'bank']

到目前为止的代码:

def remove_long_words(words_list):
    length_long = get_longest_string_length(words_list)
    
    for ele in words_list:
        if len(ele) == length_long:
            #???
            words_list.pop(???)
    
    return words_list

我首先创建了一个返回列表中最长字符串长度的函数,然后使用 for 循环遍历列表中的每个元素,然后使用 if 语句查看元素的长度是否为等于最长的字符串长度。我从那里开始遇到问题,如何使用 .pop 方法从列表中删除正确的元素?

我是否必须将列表转换为字符串,然后使用 .find 查找满足所需长度的元素的索引位置?我如何让它找到所有的出现,而不仅仅是它找到的第一个。

【问题讨论】:

  • 在遍历同一个列表时最好不要使用pop()。您可以创建列表的副本并对其进行迭代,或者创建一个新列表作为输出
  • @James, pop 要求通过 index
  • 请不要通过破坏您的帖子为他人增加工作量。通过在 Stack Exchange 网络上发帖,您已在 CC BY-SA 4.0 license 下授予 Stack Exchange 分发该内容的不可撤销的权利(即无论您未来的选择如何)。根据 Stack Exchange 政策,帖子的非破坏版本是分发的版本。因此,任何破坏行为都将被撤销。如果您想了解更多关于删除帖子的信息,请参阅:How does deleting work?

标签: python string list


【解决方案1】:

使用列表推导:

words_list = ['fish', 'barrel', 'like', 'shooting', 'sand', 'bank']
max_len = len(max(words_list, key=len))
output = [x for x in words_list if len(x) != max_len]
print(output)  # ['fish', 'barrel', 'like', 'sand', 'bank']

【讨论】:

    【解决方案2】:

    使用 Lambda 函数

    words_list = ['fish', 'barrel', 'like', 'shooting', 'sand', 'bank']
    
    list(filter(lambda x,m=max(map(len, words_list)):len(x)!=m, words_list))
    

    输出

    ['fish', 'barrel', 'like', 'sand', 'bank']
    

    【讨论】:

      【解决方案3】:

      你可以使用一个单行,但我觉得这更容易理解。

      words_list = ['fish', 'barrel', 'like', 'shooting', 'sand', 'bank']
      max = max(words_list, key=len)
      list = []
      for word in words_list:
          if len(word) < max:
              list.append(word)
      print(list)
      

      【讨论】:

        【解决方案4】:

        既然您明确询问list.pop 您可以先根据长度为每个项目创建掩码,并遍历此掩码列表的索引并弹出元素:

        maxLen = len(max(words_list))
        mask = [len(x) == maxLen for x in words_list]
        
        for i in reversed(range(len(mask))):
            if mask[i]:
                words_list.pop(i)
        
        

        确保以相反的索引顺序弹出以避免IndexError

        输出

        ['fish', 'barrel', 'like', 'sand', 'bank']
        

        【讨论】:

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