繁体   English   中英

如何编写 Python 程序来查找给定字符串中最小和最大的单词?

[英]How to Write a Python program to find smallest and largest word in a given string?

我试图在给定的字符串中找到最大最小的单词。

这是我的目标字符串。

'您好,欢迎来到python编程'

我已将字符串中的单词及其长度提取到字典中的键值对中。 下面是我写的代码。

Line='Hello, welcome to python programming '

words=[x for x in Line.split()]
print(words)

lengths=[len(word) for word in words]
print(lengths)

x = {words[i]: lengths[i] for i in range(len(words))} 
print('--'*44)
print (x)    

我得到的结果字典如下

['Hello,', 'welcome', 'to', 'python', 'programming']
[6, 7, 2, 6, 11]
*************************************************************************
{'Hello,': 6, 'welcome': 7, 'to': 2, 'python': 6, 'programming': 11}

我想对字典进行排序打印具有最高最低值的键,即最长最短的单词。

你也可以滥用collections.Counter

from collections import Counter

line = 'Hello, welcome to python programming '
c = Counter({word: len(word) for word in line.split()})

print(c.most_common(1)[0])  # ('programming', 11)
print(c.most_common()[-1])  # ('to', 2)

如果你想要一个 oneliner 列表理解,试试这个:

l = 'Hello, welcome to python programming '
print(*[i for i in l.split() if len(i) == max([len(k) for k in l.split()])]) # Gives longest word (words if multiple)
print(*[i for i in l.split() if len(i) == min([len(k) for k in l.split()])]) # Gives shortest word (words if multiple)

输出

programming
to

如果您想采用您的方法,请尝试以下操作:

x = {'Hello,': 6, 'welcome': 7, 'to': 2, 'python': 6, 'programming': 11}
sorted_x = sorted(x, key= lambda y: len(y), reverse = True)
longest_word = sorted_x[0]
shortest_word = sorted_x[-1]

使用您当前的方法:

使用max() min()

maxWord = max(x, key=x.get)
minWord = min(x, key=x.get)

print("The maximum-sized word is {} with len {}".format(maxWord, x[maxWord]))
print("The minimum-sized word is {} with len {}".format(minWord, x[minWord]))

输出

The maximum-sized word is programming with len 11
The minimum-sized word is to with len 2

备选方案

s = 'Hello, welcome to python programming '

print(max(s.split(), key=len))
print(min(s.split(), key=len))

详细说明

s = 'Hello, welcome to python programming '
maxWord = max(s.split(), key=len)
maxLen = len(maxWord)

minWord = min(s.split(), key=len)
minLen = len(minWord)

print((maxWord, maxLen))           # ('programming', 11)
print((minWord, minLen))           # ('to', 2)

单线

print((((max(s.split(), key=len), len(maxWord)),(min(s.split(), key=len), len(maxWord)))))

输出

(('programming', 11), ('to', 11))
a = "  i love flask"
a = a.split()
b = len(a[0])
c = 0
for x in a:
    s = len(x)
    if s < b:
      b = s
    elif s > c:
      c = s 
for y in a:
  k = len(y)
  if k == b:
    print (b,y)
  elif  k == c:
    print (c,y)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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