Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用单列表理解重写函数_Python_List Comprehension - Fatal编程技术网

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如果有人的答案解决了你的问题,你可能希望使用大复选框接受它作为答案。