gpt4 book ai didi

Python - 在列表中查找最短的单词

转载 作者:太空宇宙 更新时间:2023-11-04 07:18:41 26 4
gpt4 key购买 nike

大家好,据我所知,可能已经有人问过一些类似的问题,但如果您能为我尝试的问题提供更具体的解决方案,我将不胜感激。

基本上程序应该返回列表中最短的单词。最短的单词不能为空字符串。 <-- 我也不确定该怎么做。

感谢您的帮助! :)

主程序:

    n = int((input("Enter amount of words: "))
sw = st.word(n)
print("The shortest word is: {0:.s}" .format(sw))

功能:

    def word(n):

l1 = []

for i in range(n):
words = str(input("Enter word: "))
l1.append(words)

s = l1
nxt = l1

for i in range(n+1):
if s[i] < nxt[i+1]:
smallest = s[i]
if nxt[i+1] < s[i]:
smallest = nxt[i+1]
return smallest

最佳答案

您可以只使用内置 min功能:

l = ["ab", "abc", "", "fff", "gdfgfdg","a", "3455"]


print(min((word for word in l if word), key=len))
# results in: a

一些解释:

  • (l if word 中的单词)generator expression ,

  • if word 条件确保不使用空字符串,

  • key=len使用每个单词的长度来寻找最小值

关于Python - 在列表中查找最短的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29325826/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com