简体   繁体   中英

Mapper Function for finding the smallest words in a text file

Can anyone helps me with the mapper function and reducer function to find the smallest word in a text file?

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 

I assume you want to find the shortest word and do this without using a list comprehension.

min() accepts an optional key for comparison. You can use a lambda function, to get the length of the word.

words = ['longest-------', 'medium-----', 'shortest-']
shortest = min(words, key=lambda x: len(x))
print(shortest)

Another approach could be to use Python's builtin sorted().

words = ['longest-------', 'medium-----', 'shortest-']
shortest = sorted(words)[-1]
print(shortest)

For more information about builtin functions please see the documentation

first append your datas to this list k=['1111','222222','a',...] then you can use this :

print reduce(lambda  x ,y : x if  len(x) < len(y) else y , k)

or if you don't want use lambda use BIF function of list :

min( word for word in k if word) 

this get you shortest element in list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM