2017-02-09 32 views
-2

嗨的功能,我需要用一个列表理解改写单列表理解

result = [] 
for word in words: 
    wordlenpair = (word, len(word)) 
    result.append(wordlenpair) 
return result 

改写这个代码,但我堆放着:

result = [wordlenpair for word in words] 

,我不知道该怎么办与此行在这里:

wordlenpair = (word, len(word)) 
+0

只需用元组替换'wordlenpair'即可。它只是一个变量,将其替换为原始表达式。 –

+0

提示:在转换之前将循环内的代码缩短为一行。 –

+0

非常感谢,现在我明白了! – Hot41

回答

1

如果你想要一个元组列表中使用你想在列表理解中的元组:

result = [(word, len(word)) for word in words] 
+0

非常感谢你! – Hot41

+0

@ Hot41如果某人的答案解决了您的问题,您可能希望使用大复选框将其作为答案接受。 – Arman

+0

是的,但我只能在4分钟内接受它;) – Hot41