我正在寻找 最快的方式 从条件下的列表中提取所有元组成员。
实施例: 从元组列表(例如[(0,0,4),(1,0,3),(1,2,1),(4,0,0)])我需要提取所有拥有更多元素的成员在第一个元组位置中超过3,然后在第二个元组位置中超过2,然后在最后元组位置中超过1。 哪个应该在这个例子中提取(4,0,0)( - >第一个条件),什么都没有( - >第二个条件)和(0,0,4),(1,0,3)( - > last条件)。这个例子非常小,我需要在数千个元组的列表上执行它。
根据我从你的答案中产生的代码,这里是秒的结果:
my_naive1,就像EmilVikström提出的那样? 13.0360000134my_naive2 110.727999926
Tim Pietzcker 9.8329999446
Don 12.5640001297
import itertools, operator, time, copy
from operator import itemgetter
def combinations_with_replacement_counts(n, r): #(A, N) in our example.N individuals/balls in A genotypes/boxes
size = n + r - 1
for indices in itertools.combinations(range(size), n-1):
#print indices
starts = [0] + [index+1 for index in indices]
stops = indices + (size,)
yield tuple(map(operator.sub, stops, starts))
xp = list(combinations_with_replacement_counts(3,20)) # a very small case
a1=time.time()
temp=[]
for n in xp:
for n1 in xp:
for i in xp:
if i[0] <= min(n1[0],n[0]) or i[1] <= min(n1[1],n[1]) or i[2] <= min(n1[2],n[2]):
temp.append(i)
a2=time.time()
for n in xp:
for n1 in xp:
xp_copy = copy.deepcopy(xp)
for i in xp:
if i[0] > min(n[0],n[0]) or i[1] > min(n[1],n[1]) or i[2] > min(n[2],n[2]):
xp_copy.remove(i)
a3=time.time()
for n in xp:
for n1 in xp:
output = [t for t in xp if t[0]<=min(n[0],n[0]) or t[1]<=min(n[1],n[1]) or t[2]<=min(n[2],n[2])]
a4=time.time()
for n in xp:
for n1 in xp:
l1 = sorted(xp, key=itemgetter(0), reverse=True)
l1_fitered = []
for item in l1:
if item[0] <= min(n[0],n[0]):
break
l1_fitered.append(item)
l2 = sorted(l1_fitered, key=itemgetter(1), reverse=True)
l2_fitered = []
for item in l2:
if item[1] <= min(n[1],n[1]):
break
l2_fitered.append(item)
l3 = sorted(l2_fitered, key=itemgetter(2), reverse=True)
l3_fitered = []
for item in l3:
if item[2] <= min(n[2],n[2]):
break
l3_fitered.append(item)
a5=time.time()
print "soluce my_naive1, like proposed by Emil Vikström?",a2-a1
print "soluce my_naive2",a3-a2
print "soluce Tim Pietzcker",a4-a3
print "soluce Don",a5-a4
答案 0 :(得分:4)
>>> l = [(0,0,4), (1,0,3), (1,2,1), (4,0,0)]
>>> output = [t for t in l if t[0]>3 or t[1]>2 or t[2]>1]
>>> output
[(0, 0, 4), (1, 0, 3), (4, 0, 0)]
这很快,因为t[1]>2
仅在t[0]>3
为False
时进行评估(第三个条件相同)。因此,在您的示例列表中,只需要进行8次比较。
如果您使用生成器表达式,则可以节省时间和内存(取决于您对过滤后的数据的操作):
>>> l = [(0,0,4), (1,0,3), (1,2,1), (4,0,0)]
>>> for item in (t for t in l if t[0]>3 or t[1]>2 or t[2]>1):
>>> # do something with that item
答案 1 :(得分:3)
有三个列表,每个条件对应一个条件,然后使用for循环遍历输入集,将每个元组排序到正确的目标列表中。这将在O(n)(线性)时间内执行,这是此问题的最快可能的渐近运行时间。它也只会在列表上循环一次。
答案 2 :(得分:2)
如果你不关心结果项的顺序,我建议在排序列表中查找,在第一个非匹配项上有中断条件: 这会跳过列表尾巴。
from operator import itemgetter
l = [(..., ..., ...), (...)]
l1_source = sorted(l, key=itemgetter(0), reverse=True)
l1_fitered = []
for item in l1:
if item[0] <= 3:
break
l1_fitered .append(item)
l2 = sorted(l, key=itemgetter(1), reverse=True)
...