简单的python功能变得简单

时间:2015-01-13 06:04:42

标签: python python-2.7

给定一个包含一些字符串的数组,返回一个包含这些字符串长度的数组。

  x = ["andrew", "jake","linda","chris"]
  def length_array(input_array):
      w = []
      for e in input_array:
          w.append(len(e))
      return w

如何将其变为列表理解?

3 个答案:

答案 0 :(得分:4)

由于标题谈到简化给定代码,我将反对被认为是“pythonic”以使代码更简单,更易读。

在您的情况下,它可以是简单的事情:

result = map(len, arr)

输出:

>>> map(len, ["test", "test123","blah"])
[4, 7, 4]

答案 1 :(得分:3)

尝试这样:

[len(x) for x in ["andrew", "jake","linda","chris"]]

所以在你的功能中它看起来像这样:

def length_array(input_array):
    return [len(x) for x in input_array]

演示:

>>> length_array(["andrew", "jake","linda","chris"])
[6, 4, 5, 5]

答案 2 :(得分:1)

x = ["andrew", "jake","linda","chris"]

def length_array(input_array):
    w = [len(e) for e in input_array]
    return w

print length_array(x)