假设我有一个列表[12,12,12,12,13,13,13,13,14,14,14,14,14,14,14,15,15,15, etc]
我希望我的结果如下:
[12,12,12,13,13,13,14,14,14,15,15,15]
第一个列表中相同数字的数量可能会有所不同,但我想为相同数字的每个范围获取三元组。我假设我可以从第一个数字(12)
开始遍历列表并获得前3个相同的数字(12,12,12)
,然后比较数字,一旦数字12变为13,得到接下来的3个数字(13,13,13)
,等等。但我想不出一个正确做法的好方法。感谢您的任何建议。
答案 0 :(得分:3)
我会使用itertools.groupby()
来隔离相同数字的字符串,然后使用列表推导来创建三元组:
import itertools
some_list = [12,12,12,12,13,13,13,13,14,14,14,14,14,14,14,15,15,15,]
updated_list = [i for k,_ in itertools.groupby(some_list) for i in [k]*3]
assert updated_list == [12,12,12,13,13,13,14,14,14,15,15,15]
答案 1 :(得分:1)
updated_list = []
curr_number = some_list[0]
curr_count = 0
for n in some_list:
if n == curr_number
curr_count += 1
if not (curr_count > 3):
updated_list.append(n)
else:
curr_number = n
curr_count = 1
updated_list.append(n)
答案 2 :(得分:0)
似乎set set方法比itertools快一点。如果你需要它排序,更少但更快。
A = [12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15]
def with_set(A):
A = set(A)
return list(A) * 3
import itertools
def with_iter(A):
return [i for k,_ in itertools.groupby(A) for i in [k]*3]
import timeit
print("Result with set: ", timeit.timeit(lambda:with_set(A),number = 1000))
print("Result with iter: ", timeit.timeit(lambda:with_iter(A),number = 1000))
设置结果:0.008438773198370306
iter的结果:0.018557160246834882
答案 3 :(得分:0)
以下代码行是不言自明的:
A = [1, 2, 3, 4, 1, 4]
A = list(set(A)) #removes duplicates
A *= 3 #multiplies the unique list 3 times
print sorted(A) # makes a new sorted list