print the length of the longest string in the list

2020-01-20 05:21发布

问题:

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.