如何提高分割列表的速度?

时间:2018-06-11 13:03:53

标签: python performance list pandas

我只是想提高分割列表的速度。现在我有办法拆分列表,但速度不如我预期的那么快。

def split_list(lines):
        return [x for xs in lines for x in xs.split('-')]

import time

lst= []
for i in range(1000000):
    lst.append('320000-320000')

start=time.clock()
lst_new=split_list(lst)
end=time.clock()
print('time\n',str(end-start))

例如,Input

lst
 ['320000-320000', '320000-320000']

Output

lst_new
 ['320000', '320000', '320000', '320000']

我对分割的速度不满意,因为我的数据包含很多列表。

但现在我不知道是否有更有效的方法。

根据建议,我试着更具体地描述我的整个问题。

import pandas as pd

df = pd.DataFrame({ 'line':["320000-320000, 340000-320000, 320000-340000",
                            "380000-320000",
                            "380000-320000,380000-310000",
                            "370000-320000,370000-320000,320000-320000",
                            "320000-320000, 340000-320000, 320000-340000",
                            "380000-320000",
                            "380000-320000,380000-310000",
                            "370000-320000,370000-320000,320000-320000",
                            "320000-320000, 340000-320000, 320000-340000",
                            "380000-320000",
                            "380000-320000,380000-310000",
                            "370000-320000,370000-320000,320000-320000"], 'id':[1,2,3,4,5,6,7,8,9,10,11,12],})

def most_common(lst):
    return max(set(lst), key=lst.count)

def split_list(lines):
    return [x for xs in lines for x in xs.split('-')]

df['line']=df['line'].str.split(',')
col_ix=df['line'].index.values
df['line_start'] = pd.Series(0, index=df.index)
df['line_destination'] = pd.Series(0, index=df.index)

import time 
start=time.clock()

for ix in col_ix:
    col=df['line'][ix]
    col_split=split_list(col)
    even_col_split=col_split[0:][::2]
    even_col_split_most=most_common(even_col_split)
    df['line_start'][ix]=even_col_split_most

    odd_col_split=col_split[1:][::2]

    odd_col_split_most=most_common(odd_col_split)
    df['line_destination'][ix]=odd_col_split_most

end=time.clock()
print('time\n',str(end-start))

del df['line']
print('df\n',df)

Input

df
 id                                         line
0    1  320000-320000, 340000-320000, 320000-340000
1    2                                380000-320000
2    3                  380000-320000,380000-310000
3    4    370000-320000,370000-320000,320000-320000
4    5  320000-320000, 340000-320000, 320000-340000
5    6                                380000-320000
6    7                  380000-320000,380000-310000
7    8    370000-320000,370000-320000,320000-320000
8    9  320000-320000, 340000-320000, 320000-340000
9   10                                380000-320000
10  11                  380000-320000,380000-310000
11  12    370000-320000,370000-320000,320000-320000

Output

df
 id  line_start  line_destination
0    1     320000    320000
1    2     380000    320000
2    3     380000    320000
3    4     370000    320000
4    5     320000    320000
5    6     380000    320000
6    7     380000    320000
7    8     370000    320000
8    9     320000    320000
9   10     380000    320000
10  11     380000    320000
11  12     370000    320000

您可以认为line的数量(例如320000-32000代表路线的起点和终点)。

Expected: 让代码运行得更快。(我无法承受代码的速度)

3 个答案:

答案 0 :(得分:3)

'-'.join(lst).split('-')

似乎要快得多:

>>> timeit("'-'.join(lst).split('-')", globals=globals(), number=10)
1.0838123590219766
>>> timeit("[x for xs in lst for x in xs.split('-')]", globals=globals(), number=10)
3.1370303670410067

答案 1 :(得分:2)

根据您对列表的处理方式,使用genertor可能会稍快一些。

如果您需要保存输出,那么列表解决方案会更快。

如果您只需要迭代单词一次,就可以通过使用生成器来消除一些开销。

def split_list_gen(lines):
    for line in lines:
        yield from line.split('-')

基准

import time

lst = ['32000-32000'] * 10000000

start = time.clock()
for x in split_list(lst):
    pass
end = time.clock()
print('list time:', str(end - start))

start = time.clock()
for y in split_list_gen(lst):
    pass
end = time.clock()
print('generator time:', str(end - start))

输出

发电机解决方案的速度一直快10%左右。

list time: 0.4568295369982612
generator time: 0.4020671741918084

答案 2 :(得分:1)

将更多的工作推到Python级别之下似乎提供了一个小的加速:

In [7]: %timeit x = split_list(lst)
407 ms ± 876 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [8]: %timeit x = list(chain.from_iterable(map(methodcaller("split", "-"), lst
   ...: )))
374 ms ± 2.67 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

methodcaller创建一个为您调用函数的函数:

methodcaller("split", "-")(x) == x.split("-")

chain.from_iterable创建一个迭代器,该迭代器由一组可迭代的元素组成:

list(chain.from_iterable([[1,2], [3,4]])) == [1,2,3,4]

mapmethodcaller返回的函数ping到您的字符串列表中,生成一个适用于from_iterable展平的可迭代列表。这种功能更强大的方法的好处是所涉及的功能都是用C语言实现的,可以使用 in Python对象,而不是在 上运行的Python字节代码Python对象。

相关问题