问题
让我们假设我们正在使用大型数据集,为了简单起见,我们在这个问题中使用了这个较小的数据集:
dataset = [["PLANT", 4,11],
["PLANT", 4,12],
["PLANT", 34,4],
["PLANT", 6,5],
["PLANT", 54,45],
["ANIMAL", 5,76],
["ANIMAL", 7,33],
["Animal", 11,1]]
我们想找出哪个列具有最长的连续值范围,哪个是找出最快的方法,哪个是最佳列?
天真的方法
我发现它很快可以按每列
进行分类sortedDatasets = []
for i in range(1,len(dataset[0]):
sortedDatasets.append(sorted(dataset,key=lambda x: x[i]))
但是这里出现了滞后部分:我们可以从这里继续为每个已排序的数据集做一个for loop
,并计算连续的元素,但是当处理for loops
时,python非常慢。
现在我的问题:是否有比这种天真的方法更快的方法,甚至可能还有这些2D容器的内置函数?
更新
更准确地说,范围的含义可以用这个伪算法来描述 - 这包括递增current value == next value
:
if nextValue > current Value +1:
{reset counter}
else:
{increment counter}
答案 0 :(得分:5)
您可以使用groupby
以合理的效率执行此操作。我将分阶段进行此操作,以便您了解它的工作原理。
from itertools import groupby
dataset = [
["PLANT", 4, 11],
["PLANT", 4, 12],
["PLANT", 34, 4],
["PLANT", 6, 5],
["PLANT", 54, 45],
["ANIMAL", 5, 76],
["ANIMAL", 7, 33],
["ANIMAL", 11, 1],
]
# Get numeric columns & sort them in-place
sorted_columns = [sorted(col) for col in zip(*dataset)[1:]]
print sorted_columns
print
# Check if tuple `t` consists of consecutive numbers
keyfunc = lambda t: t[1] == t[0] + 1
# Search for runs of consecutive numbers in each column
for col in sorted_columns:
#Create tuples of adjacent pairs of numbers in this column
pairs = zip(col, col[1:])
print pairs
for k,g in groupby(pairs, key=keyfunc):
print k, list(g)
print
<强>输出强>
[[4, 4, 5, 6, 7, 11, 34, 54], [1, 4, 5, 11, 12, 33, 45, 76]]
[(4, 4), (4, 5), (5, 6), (6, 7), (7, 11), (11, 34), (34, 54)]
False [(4, 4)]
True [(4, 5), (5, 6), (6, 7)]
False [(7, 11), (11, 34), (34, 54)]
[(1, 4), (4, 5), (5, 11), (11, 12), (12, 33), (33, 45), (45, 76)]
False [(1, 4)]
True [(4, 5)]
False [(5, 11)]
True [(11, 12)]
False [(12, 33), (33, 45), (45, 76)]
现在,要攻击您的实际问题:
from itertools import groupby
dataset = [
["PLANT", 4, 11],
["PLANT", 4, 12],
["PLANT", 34, 4],
["PLANT", 6, 5],
["PLANT", 54, 45],
["ANIMAL", 5, 76],
["ANIMAL", 7, 33],
["ANIMAL", 11, 1],
]
# Get numeric columns & sort them in-place
sorted_columns = [sorted(col) for col in zip(*dataset)[1:]]
# Check if tuple `t` consists of consecutive numbers
keyfunc = lambda t: t[1] == t[0] + 1
#Search for the longest run of consecutive numbers in each column
runs = []
for i, col in enumerate(sorted_columns, 1):
pairs = zip(col, col[1:])
m = max(len(list(g)) for k,g in groupby(pairs, key=keyfunc) if k)
runs.append((m, i))
print runs
#Print the highest run length found and the column it was found in
print max(runs)
<强>输出强>
[(3, 1), (1, 2)]
(3, 1)
FWIW,这可以压缩成一行。它更有效率,因为它使用了几个生成器表达式而不是列表推导,但它不是特别易读:
print max((max(len(list(g))
for k,g in groupby(zip(col, col[1:]), key=lambda t: t[1] == t[0] + 1) if k), i)
for i, col in enumerate((sorted(col) for col in zip(*dataset)[1:]), 1))
我们可以通过一些小的改动来处理你的新的连续序列定义。
首先,如果排序列中相邻数字对之间的差异为&lt; = 1,我们需要一个返回True
的键函数。
def keyfunc(t):
return t[1] - t[0] <= 1
而不是采用与该关键函数匹配的序列的长度,我们现在做一些简单的算术来查看序列中值范围的大小。
def runlen(seq):
return 1 + seq[-1][1] - seq[0][0]
全部放在一起:
def keyfunc(t):
return t[1] - t[0] <= 1
def runlen(seq):
return 1 + seq[-1][1] - seq[0][0]
# Get numeric columns & sort them in-place
sorted_columns = [sorted(col) for col in zip(*dataset)[1:]]
#Search for the longest run of consecutive numbers in each column
runs = []
for i, col in enumerate(sorted_columns, 1):
pairs = zip(col, col[1:])
m = max(runlen(list(g)) for k,g in groupby(pairs, key=keyfunc) if k)
runs.append((m, i))
print runs
#Print the highest run length found and the column it was found in
print max(runs)
如评论中所述,max
如果其arg为空序列则会引发ValueError
。处理它的一种简单方法是将max
调用包装在try..except
块中。如果异常很少发生,这非常有效,try..except
实际上比异常if...else
逻辑更快,但不会引发异常。所以我们可以做这样的事情:
run = (runlen(list(g)) for k,g in groupby(pairs, key=keyfunc) if k)
try:
m = max(run)
except ValueError:
m = 0
runs.append((m, i))
但如果这种异常经常发生,那么使用其他方法会更好。
这是一个使用完全成熟的生成器函数find_runs
代替生成器表达式的新版本。在find_runs
开始处理列数据之前,yield
只需max
为零,因此runlen
将始终至少有一个要处理的值。我已经内联runs
计算以节省额外函数调用的开销。此重构还可以更轻松地在列表解析中构建from itertools import groupby
dataset = [
["PLANT", 4, 11, 3],
["PLANT", 4, 12, 5],
["PLANT", 34, 4, 7],
["PLANT", 6, 5, 9],
["PLANT", 54, 45, 11],
["ANIMAL", 5, 76, 13],
["ANIMAL", 7, 33, 15],
["ANIMAL", 11, 1, 17],
]
def keyfunc(t):
return t[1] - t[0] <= 1
def find_runs(col):
pairs = zip(col, col[1:])
#This stops `max` from choking if we don't find any runs
yield 0
for k, g in groupby(pairs, key=keyfunc):
if k:
#Determine run length
seq = list(g)
yield 1 + seq[-1][1] - seq[0][0]
# Get numeric columns & sort them in-place
sorted_columns = [sorted(col) for col in zip(*dataset)[1:]]
#Search for the longest run of consecutive numbers in each column
runs = [(max(find_runs(col)), i) for i, col in enumerate(sorted_columns, 1)]
print runs
#Print the highest run length found and the column it was found in
print max(runs)
列表。
[(4, 1), (2, 2), (0, 3)]
(4, 1)
<强>输出强>
String from = intent.getStringExtra("from");
if ("ActivityB".equals(from)) {....}