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

时间:2019-04-17 10:06:01

标签: python dictionary

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

这是我的目标字符串。

  
    

'您好,欢迎使用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}

我想排序字典并打印键,这些键具有最高最低值,即最长最短的单词。

4 个答案:

答案 0 :(得分:2)

您还可以滥用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)

答案 1 :(得分:1)

如果您想了解单线列表,请尝试以下操作:

    $query = $conn->query("SELECT * FROM `task` WHERE status != 'Done' ORDER BY `id` ASC");

输出

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

答案 2 :(得分: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))

答案 3 :(得分:0)

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)