Python 使用单列表理解重写函数
嗨,我需要用一个列表重写这个代码Python 使用单列表理解重写函数,python,list-comprehension,Python,List Comprehension,嗨,我需要用一个列表重写这个代码 result = [] for word in words: wordlenpair = (word, len(word)) result.append(wordlenpair) return result 但我认为: result = [wordlenpair for word in words] 我不知道该怎么处理这句话: wordlenpair = (word, len(word)) 如果需要元组列表,请使用列表理解中需要的元组:
result = []
for word in words:
wordlenpair = (word, len(word))
result.append(wordlenpair)
return result
但我认为:
result = [wordlenpair for word in words]
我不知道该怎么处理这句话:
wordlenpair = (word, len(word))
如果需要元组列表,请使用列表理解中需要的元组:
result = [(word, len(word)) for word in words]
只需将
wordlenpair
替换为元组即可。它只是一个变量,用它代替原来的表达式。提示:在转换之前,将循环中的代码缩短为一行。非常感谢,现在我看到了!非常感谢@Hot41如果有人的答案解决了你的问题,你可能希望使用大复选框接受它作为答案。