print the length of the longest string in the list

谁说胖子不能爱 提交于 2019-12-26 09:03:06

问题


I am having difficulties print the length of the longest string in the list which is kevin07 which should equal to 7.

My current solution prints all 3 item lengths.

names = ['ron', 'james', 'kevin07']

best = 0

for index in range(len(names)):
    if len(names[index]) > best:
        best = len(names[index])
        print(best)

回答1:


names = ['ron', 'james', 'kevin07']

best = 0

for index in range(len(names)):
    if len(names[index]) > best:
        best = len(names[index])

print(best)

Output:

7

Explanation:

You need to move the print(best) outside of loop




回答2:


You're trying to find the maximum by length:

item = max(names, key=len)
print(len(item))

You could also be a bit more direct:

print(max(len(x) for x in names))

...though you won't know what the item is if you decide to go this way.




回答3:


For example:

names = ['ron', 'james', 'kevin07']
best = max([len(i) for i in names])
print(best)



回答4:


Please consider this approach that solves your problem:

names = ['ron', 'james', 'kevin07']

best = 0

for name in names:
    if len(name) > best:
        best = len(name)

print(best)

The main problem with your code was that you printed best in every step of you loop.

The other thing I changed is the proper usage of a range-based loop. There is actually no need to access the elements of you list via index.



来源:https://stackoverflow.com/questions/50434088/print-the-length-of-the-longest-string-in-the-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!