我按照排序顺序输入,例如:
let autocompleteController = GMSAutocompleteViewController()
autocompleteController.navigationController?.navigationBar.barTintColor = UIColor.blue
autocompleteController.tintColor = UIColor.blue
autocompleteController.primaryTextHighlightColor = UIColor.jnlyDarkGrey
autocompleteController.primaryTextColor = UIColor.black
autocompleteController.secondaryTextColor = UIColor.gray
autocompleteController.tableCellBackgroundColor = UIColor.white
我想计算每个数字出现的次数。这给出了输出:
L = [5,5,7,7,7,7,9,10,12,14]
我不需要存储原始值。我也不想使用groupby。这是因为我将使用pypy运行我的代码,这样可以最好地加速简单循环。
我可以使用以下方式无效地完成:
[2,4,1,1,1,1]
是否有一个简单的线性时间解决方案,可能只有一个for循环?
答案 0 :(得分:2)
如果你有非常大的数据,写一个小函数来提高效率。
L1 = [1, 1, 1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 8, 8, 8, 8, 8, 8, 9]
L2 = [1, 1, 1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 8, 8, 8, 8, 8, 8, 8]
def countr(lst):
res = []
count = 1
for i in range(len(lst) - 1):
if lst[i] == lst[i + 1]:
count += 1
else:
res.append(count)
count = 1
res.append(count)
return res
countr(L1)
# [4, 2, 1, 1, 1, 1, 1, 7, 1]
countr(L2)
# [4, 2, 1, 1, 1, 1, 1, 8]
答案 1 :(得分:1)
这是为Counter创建的:
>>> from collections import Counter
>>> counts = Counter([5,5,7,7,7,7,9,10,12,14])
>>> [counts[i] for i in sorted(counts.keys())]
[2, 4, 1, 1, 1, 1]
或者,如果你想优化内存使用,这里有一个可以迭代的函数,甚至是一个从文件中获取数字的生成器:
def run_lengths(lst):
previous_val = None
num_vals = 0
for i in lst:
if previous_val is None:
previous_val = i
if i == previous_val:
num_vals += 1
continue
yield num_vals
previous_val = i
num_vals = 1
if num_vals:
yield num_vals
print(list(run_lengths([5,5,7,7,7,7,9,10,12,14]))) # Returns [1, 2, 4, 1, 1, 1]
def file_generator(file_path):
with open(file_path, 'r') as f:
for l in f:
yield int(l.strip())
print(list(run_lengths(file_generator('my/huge/file.dat'))))