删除列表中长度为x的所有字符串
我的修订实践之一涉及创建一个函数,该函数删除列表中具有最高字符串长度的所有字符串。
预期输出:
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 找到满足所需长度的元素的索引位置?我如何让它找到所有出现的事件,而不仅仅是它找到的第一个。
回答
使用列表理解:
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']