首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用于在文本文件中查找最小单词的映射器函数

用于在文本文件中查找最小单词的映射器函数
EN

Stack Overflow用户
提问于 2017-08-17 00:21:41
回答 2查看 253关注 0票数 0

有没有人能帮我用mapper函数和reducer函数在文本文件中找到最小的单词?

代码语言:javascript
复制
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 
EN

回答 2

Stack Overflow用户

发布于 2017-08-17 00:40:01

我假设您想要找到最短的单词,并在不使用列表理解的情况下这样做。

min()接受一个用于比较的可选键。您可以使用lambda函数来获取单词的长度。

代码语言:javascript
复制
words = ['longest-------', 'medium-----', 'shortest-']
shortest = min(words, key=lambda x: len(x))
print(shortest)

另一种方法是使用Python的内置sorted()。

代码语言:javascript
复制
words = ['longest-------', 'medium-----', 'shortest-']
shortest = sorted(words)[-1]
print(shortest)

有关内置函数的更多信息,请参阅documentation

票数 0
EN

Stack Overflow用户

发布于 2017-08-17 00:49:07

首先将您的数据附加到此列表k=['1111','222222','a',...],然后您可以使用以下命令:

代码语言:javascript
复制
print reduce(lambda  x ,y : x if  len(x) < len(y) else y , k)

或者如果你不想使用lambda,可以使用list的BIF函数:

代码语言:javascript
复制
min( word for word in k if word) 

这将使您获得列表中最短的元素

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45718617

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档