有没有人能帮我用mapper函数和reducer函数在文本文件中找到最小的单词?
import sys #importing from the system
smallest = None
for line in sys.stdin: #taking input from the system
line = line.strip() #leaving the unwanted whitespaces
words = line.split("\t") #spliting the words with delimiter TAB
smallest= min([len(word) for word in words]) #finding the smallest word
print ('%s' % (smallest)) #printing the snallest word 发布于 2017-08-17 00:40:01
我假设您想要找到最短的单词,并在不使用列表理解的情况下这样做。
min()接受一个用于比较的可选键。您可以使用lambda函数来获取单词的长度。
words = ['longest-------', 'medium-----', 'shortest-']
shortest = min(words, key=lambda x: len(x))
print(shortest)另一种方法是使用Python的内置sorted()。
words = ['longest-------', 'medium-----', 'shortest-']
shortest = sorted(words)[-1]
print(shortest)有关内置函数的更多信息,请参阅documentation
发布于 2017-08-17 00:49:07
首先将您的数据附加到此列表k=['1111','222222','a',...],然后您可以使用以下命令:
print reduce(lambda x ,y : x if len(x) < len(y) else y , k)或者如果你不想使用lambda,可以使用list的BIF函数:
min( word for word in k if word) 这将使您获得列表中最短的元素
https://stackoverflow.com/questions/45718617
复制相似问题