2

我想知道你是否可以帮助我加快我的 python 脚本。

我有两个清单:

a=['a','b','c','d','e','f','g','h','i','j']

b=['b','f','g','j']

我想创建一个列表,其中将包含 b 的元素,但长度为 a,其中不在 b 中的元素替换为其他内容,比方说'-999'。另外,我不想使用实际元素(a,b,c ...),而是用 b 中的元素索引替换它。所以它看起来像这样:

c=['-999',0,'-999','-999','-999', 1, 2,'-999','-999',3] 

我现在的代码是:

c=[]

counter=0

for each in a:
    if each in b:
        c.append(counter)
        counter+=1
    else:
        c.append('-999')

它工作正常,但是,在现实生活中,我的列表 a 有 600 000 个元素长,实际上有 7 个 b 列表我需要迭代它们,所有元素也在 3k 到 250k 之间。

关于如何加快速度的任何想法?

4

2 回答 2

6

如果其中的元素b是唯一的,那么您可以尝试以下操作:

In [76]: a=['a','b','c','d','e','f','g','h','i','j']

In [77]: b=['b','f','g','j']

In [78]: dic={x:i for i,x in enumerate(b)}

In [79]: dic
Out[79]: {'b': 0, 'f': 1, 'g': 2, 'j': 3}

In [81]: [dic.get(x,'-999') for x in a]
Out[81]: ['-999', 0, '-999', '-999', '-999', 1, 2, '-999', '-999', 3]

对于重复的项目,您可以使用defaultdict(list)

In [102]: a=['a','b','c','d','e','f','g','b','h','i','f','j']

In [103]: b=['b','f','g','j','b','f']

In [104]: dic=defaultdict(list)

In [105]: for i,x in enumerate(b):
    dic[x].append(i)
   .....:     

#now convert every value(i.e list) present in dic to an iterator.

In [106]: dic={x:iter(y) for x,y in dic.items()}  

In [107]: [next(dic[x]) if x in dic else '-999' for x in a]  #call next() if the key 
                                                             #is present else use '-999'
Out[107]: ['-999', 0, '-999', '-999', '-999', 1, 2, 4, '-999', '-999', 5, 3]
于 2013-01-18T12:36:24.393 回答
0

更简单的东西:

a=['a','b','c','d','e','f','g','h','i','j']

b=['b','f','g','j']

for i,x in enumerate(a):
    a[i] = b.index(x) if x in b else -999

输出:

[-999, 0, -999, -999, -999, 1, 2, -999, -999, 3]

分析:

OP的方法:

>>> 
len(a) = 10000
len(b) = 5000
Time = 0:00:01.063000

方法一:

c=[]
for i,x in enumerate(a):
    c.append(b.index(x) if x in b else -999)

>>> 
len(a) = 10000
len(b) = 5000
Time = 0:00:01.109000

Ashwini Chaudhary 方法:

>>> 
len(a) = 10000
len(b) = 5000
Time = 0:00:00
于 2013-01-18T12:39:29.027 回答