列表中最长字的长度 [英] Length of longest word in a list

查看:131
本文介绍了列表中最长字的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更长的最长词的蟒蛇方式是什么:

What is the more pythonic way of getting the length of the longest word:

len(max(words,key = len))

或:

max )for w in words)

还有别的什么? words 是字符串列表。
我发现我需要经常这样做,并在定时与几个不同的样本大小后,第一种方法似乎是一直更快,尽管看起来效率低于面值( len 被调用两次似乎没有关系 - 在这种形式的C代码更多发生?)。

Or.. something else? words is a list of strings. I am finding I need to do this often and after timing with a few different sample sizes the first way seems to be consistently faster, despite seeming less efficient at face value (the redundancy of len being called twice seems not to matter - does more happen in C code in this form?).

推荐答案

我认为两者都行,但我认为除非速度是一个很大的考虑, max len(w)for w in words)是最易读的。

I think both are OK, but I think that unless speed is a big consideration that max(len(w) for w in words) is the most readable.

当我看着他们时,什么 len(max(words,key = len))正在做,我还是错,直到我想起来更多。代码应该是显而易见的,除非有一个很好的理由不是。

When I was looking at them, it took me longer to figure out what len(max(words, key=len)) was doing, and I was still wrong until I thought about it more. Code should be immediately obvious unless there's a good reason for it not to be.

从其他帖子(和我自己的测试)清楚, 。但它不是因为他们都是狗慢。除非代码在关键路径上,否则不值得担心。

It's clear from the other posts (and my own tests) that the less readable one is faster. But it's not like either of them are dog slow. And unless the code is on a critical path it's not worth worrying about.

最终,我认为更易读的是Pythonic。

Ultimately, I think more readable is more Pythonic.

另外,对于同样的任务,这种情况下的Python 2明显比Python 3快。

As an aside, this one of the few cases in which Python 2 is notably faster than Python 3 for the same task.

这篇关于列表中最长字的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆