例如:
def get_longest_name(a_list):
count = 0
for i in a_list:
if len(i) > count:
count = len(i)
word = i
return word
def main():
print("1.", get_longest_name(["Candide", "Jessie", "Kath", "Amity",
"Raeanne"]))
print("2.", get_longest_name(["Josephine", "Jessie", "Penelope", "Jin",
"Rosamunda", "Annabelle"]))
print("3.", get_longest_name(["Alan", "Jess", "Amity", "Rosalie",
"Raeanne"]))
print("4. ", "***", get_longest_name(["Jo", "Jai", "Jen", "Jing", "Joey",
"Jess"]), "***", sep = "")
print("5. ", "***", get_longest_name([]), "***", sep = "")
print("6.", "***" + get_longest_name([""]) + "***")
main()
输出如下:
^{pr2}$我已经得到了三个正确的输出(三个最长的名称),但是对于第四个输出,没有最长的名称存在,第五个、第六个也没有。我希望输出如下:
1. Candide
2. Josephine
3. Rosalie
4. ******
5. ******
6. ******
我不知道怎么修。在
您只需使用内置的
max()
函数:你对你想要达到的成果含糊其辞。和你说的不同,坎迪德和雷恩的长度相等。同样,在第二和第三种情况下也有长度相等的名字。在第四个字母中,有三个相同长度的名字。在
假设您要为[]、['']和包含长度相等的名称的列表输出
‘******’
,或者该名称的长度大于列表中任何其他名称的长度,那么我的代码如下:因此,这里已经有了很好的解决方案,但是如果您想为自己创建查找max的逻辑,如果不是max,则在不使用内置max()函数的情况下打印(“*******”),那么请看一下:
让我们分三步来解决您的问题:
出于测试目的,假设列表为:
假设您希望如果三个字符的长度相同,则打印(“*******”),那么首先我们必须过滤出列表中有多少字符具有相同的长度,如果超过三个字符的长度相同,则打印(“*****”)。现在进行筛选时,我们可以使用filter、lambda和list comprehension,但这里我将使用非常简单易读的方法:
^{pr2}$干得好现在我们进入第二步:
我们已经检查过,如果一个列表有超过三个相同的len字符,那么将这个len添加到一个名为more_than_3的列表中,现在我们将看到这个问题的第二部分假设如果列表没有相同长度的字符,那么我们要在该列表中存储最长的单词字符,因此:
现在我们已经完成了这个问题需要的所有逻辑部分,现在让我们做最后一个部分,检查是否有多个“超过”3的列表是空的而不是“打印”的最长单词,如果“多于”3个列表不为空而不是“打印”(“*******”),非常简单:
所有组合:
相关问题 更多 >
编程相关推荐