【问题标题】:Best way to split strings分割字符串的最佳方法
【发布时间】:2012-11-16 22:41:42
【问题描述】:

我有一个包含名字和姓氏的列表,比如这个:

names = ["John Smith", "Rob Julian", "Eric Walls"]

我只想获取此列表中的名字。

我做到了:

first_names = [n.split(" ")[0] for n in names]

这给了我想要的结果。

但是在我看来这很丑陋,有没有更好的方法来实现这个目标?

【问题讨论】:

  • 这正是我要写的,除了我会省略" "
  • 如果你觉得这很丑,试试用 C 来做吧。

标签: python string list split list-comprehension


【解决方案1】:

是的,但不是真的。性能方面,你最好用你所拥有的。

first_names = []
for n in names:
    first_names.append(n.split()[0])

会起作用,但我喜欢 python 中的列表理解。我的意思是有什么问题

first_names = [n.split()[0] for n in names]

为了好玩,您还可以执行以下操作。我想如果你正在处理一个非常大的列表,这可能会有最好的性能。但是,您可能想先调查一下。

first = lambda n : n.split()[0]
first_names = [first(name) for name in names]

为了使这一点更全面,您还可以使用 lambda 对其进行映射。

first = lambda n : n.split()[0]
first_names = map(first,names)

每个 cmets,我正在添加另一种方式

from operator import itemgetter
first_names = map(itemgetter(0), map(str.split, names))

总之,是的,还有其他方法可以做到这一点。

但您的原件似乎是最受欢迎的。如果速度是一个问题,您可能需要修补其他问题。

随时间更新

不是最科学的,但使用大约 350 万个名字的列表,我运行上面调用文件 n0-4 并运行time n0;time n1; time n2; time n3; time n4 这是我的结果。看起来好像原始列表理解是我机器上最快的。

real    0m8.433s
user    0m7.064s
sys     0m1.288s

real    0m8.213s
user    0m6.852s
sys     0m1.300s

real    0m8.581s
user    0m7.240s
sys     0m1.264s

real    0m8.374s
user    0m7.164s
sys     0m1.140s

real    0m11.890s
user    0m10.101s
sys     0m1.672s

(我以不同的顺序运行了几次,时间是一致的。)

【讨论】:

  • 这不是更快,但不错的尝试。 In [1]: %timeit first_names = [first(name) for name in names]100000 loops, best of 3: 2.81 us per loopIn [2]: %timeit [n.split()[0] for n in names]100000 loops, best of 3: 2 us per loopIn [3]: %timeit map(itemgetter(0), map(str.split, names))100000 loops, best of 3: 3.79 us per loop
  • 谢谢,我正要自己运行这些测试。我想我会克制自己,给自己弄点晚餐。
  • 使用operator.itemgetter(0) 代替lambda 更好:docs.python.org/2/library/operator.html#operator.itemgetter
【解决方案2】:

我认为最好的性能是使用匿名函数和map 函数:

first = lambda n : n.split()[0]

first_names = map(first,names)

【讨论】:

    【解决方案3】:

    我认为你的方法很棒,但是

    first_names = [n.split()[0] for n in names]
    

    有点厉害。

    阅读this

    【讨论】:

      【解决方案4】:

      我不会说它更好,但这是另一种方法:

      >>> names = ["John Smith", "Rob Julian", "Eric Walls"]
      >>> first = lambda x:x.split()[0]
      >>> map(first, names)
      ['John', 'Rob', 'Eric']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-15
        • 1970-01-01
        • 1970-01-01
        • 2016-08-29
        • 1970-01-01
        • 1970-01-01
        • 2017-12-20
        相关资源
        最近更新 更多