![](/img/trans.png)
[英]How to efficiently check if an element is in a list of lists in python
[英]How to efficiently check and add if an element does not exist in a nested list?
我有一个巨大的嵌套列表,它的元素是单词字符串,格式如下:
[[0,'+','the','+','quick','+','brown','+','fox','+','jumps','over','+','the','+','lazy','+','dog','+',908]
...,
['Now','+','is','+', 'the','+', 'time','+', 'for','+', 'all','+', 67,'+', 'men']]
但是,我发现有些元素没有+
分隔符。 例如,在子列表一中:
[0,'+','the','+','quick','+','brown','+','fox','+','jumps','over','+','the','+','lazy','+','dog','+',908]
在'jumps','over'
存在+
。 对于带有长子列表的大型嵌套列表,在没有分隔符的元素之间添加+
分隔符的最有效方法是什么?
预期的输出应如下所示:
[[0,'+','the','+','quick','+','brown','+','fox','+','jumps','+','over','+','the','+','lazy','+','dog','+',908]
...,
['Now','+','is','+', 'the','+', 'time','+', 'for','+', 'all','+', 67,'+', 'men']]
有点贪心:
cleansed_lists = [[word for word in sentence if word != '+'] for sentence in nested_list]
result = []
for sentence in cleansed_lists:
new_list = ['+'] * (2 * len(sentence) - 1)
new_list[::2] = sentence
result.append(new_list)
时间复杂度:
假设N
是您的外部列表的长度,而n
是每个内部列表(您的句子)的平均长度。
第1行 :我们使用O(1)操作(即if word != '+'
)遍历一次外部列表,一次迭代每个内部列表。 因此,第1行的时间复杂度为O(n * N) 。
第3-6行 :我们一次遍历外部列表(第3行), 相当于列表的大小是内部列表大小的两倍(第4行),列表的其他所有元素则是内部列表大小的两倍(第4行) 5)。 这会产生O(N *(2n + n))的时间复杂度,从而简化为O(n * N) 。
= O(n*N) + O(N*(2n+n))
= O(n*N) + O(N*3n)
= O(n*N) + O(N*n)
= O(n*N)
因此,最终复杂度为O(n * N) 。
x = [[0,'+','the','+','quick','+','brown','+','fox','+','jumps','over','+','the','+','lazy','+','dog','+',908],
['Now','+','is','+', 'the','+', 'time','+', 'for','+', 'all','+', 67,'+', 'men']]
x = [[i for i in item if i != '+'] for item in x]
print([sum([[a,b] for a, b in zip(item, ['+' for _ in range(len(item))])], []) for item in x ])
输出量
[[0, '+', 'the', '+', 'quick', '+', 'brown', '+', 'fox', '+', 'jumps', '+', 'over', '+', 'the', '+', 'lazy', '+', 'dog', '+', 908, '+'], ['Now', '+', 'is', '+', 'the', '+', 'time', '+', 'for', '+', 'all', '+', 67, '+', 'men', '+']]
我尝试了两种方法,但没有较大的嵌套列表:
data = [0, '+', 'the', '+', 'quick', '+', 'brown', '+', 'fox', '+',
'jumps', 'over', '+', 'the', '+', 'lazy', '+', 'dog', '+', 908]
def func_1():
for i in range(1, len(data), 2):
if data[i] != '+':
data.insert(i, '+')
def func_2():
real_data = [val for val in data if val != '+']
spliter = '+'*len(real_data)
[i for ab in zip(real_data, spliter) for i in ab][:-1]
%timeit func_1()
%timeit func_2()
最终结果是:
981 ns ± 17.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
3.24 µs ± 101 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
也许您可以试试〜祝您好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.