我在python中有一些整数列表:
[[2, 8, 10, 500, 502], [1, 4, 5, 401]]
如何根据列表中数字之间的差异将值扩展为连续范围,以便得到如下内容:
[[2, 3, 4, 5, 6, 7, 8, 9, 10, 500, 501, 502], [1, 2, 3, 4, 5, 401]]
所以,基本上,如果列表中的项目之间的差异小于100,则只将一组数字扩展为一个完整范围?
答案 0 :(得分:1)
这很难看,但试试这个:
def list_expand(x):
new_list = []
while True:
if len(x) < 2:
new_list.append(x[0])
break
m = min(x)
x.remove(m)
if abs(m - min(x)) < 100:
new_list.extend(range(m, min(x)))
else:
new_list.append(m)
return new_list
它通过了这些测试:
assert list_expand([99, 0, 198]) == range(0, 199)
assert list_expand([100, 0, 200]) == [0, 100, 200]
assert list_expand([2, 8, 10, 500, 502]) == range(2, 11) + range(500, 503)
assert list_expand([1, 4, 5, 401]) == range(1, 6) + [401]
答案 1 :(得分:1)
这是另一个版本,可能更短:
In [7]: from collections import OrderedDict
In [107]: def foo(l):
...: l=sorted(l)
...: t = l + [e for i, v in enumerate(l[1:]) for e in range(l[i], v) if v-l[i]<100]
...: return list(OrderedDict.fromkeys(sorted(t)))
In [108]: assert foo([99, 0, 198]) == range(0, 199)
...: assert foo([100, 0, 200]) == [0, 100, 200]
...: assert foo([2, 8, 10, 500, 502]) == range(2, 11) + range(500, 503)
...: assert foo([1, 4, 5, 401]) == range(1, 6) + [401]
答案 2 :(得分:1)
用itertools.izip_longest
和三元一样的操作被黑客攻击:)
from itertools import izip_longest as zip
def list_expand(c):
c = sorted(c)
return [k for i,j in zip(c,c[1:],fillvalue=0) for k in [[i],range(i,j)][0<=j-i<100]]
assert list_expand([99, 0, 198]) == range(0, 199)
assert list_expand([100, 0, 200]) == [0, 100, 200]
assert list_expand([2, 8, 10, 500, 502]) == range(2, 11) + range(500, 503)
assert list_expand([1, 4, 5, 401]) == range(1, 6) + [401]
答案 3 :(得分:0)
a = [2,8,10,500,502]
def expand_list(a):
for element in a:
if element < 10:
for i in range(element):
if i not in a:
a.append(i)
return sorted(a)
print expand_list(a)
这可能不是最佳解决方案,但我把这作为时间挑战;)
编辑:这应该通过测试,虽然我不确定它是否正确。但我想我会留下它。
a = [8, 2, 10, 500, 502]
def expand_list(a):
a = sorted(a)
for i in range(len(a)):
if i > 0:
if (a[i] - a[i-1]) < 100:
for j in range(a[i-1], a[i]):
if j not in a:
a.append(j)
return sorted(a)
print expand_list(a)
答案 4 :(得分:0)
这应该有效:
v = [100, 0, 200]
v = sorted(v)
exp = []
for i, ele in enumerate(v[1:]):
if ele - v[i] < 100:
exp.extend(range(v[i], ele))
exp.extend([ele]) # to add the last element of the range
if not exp:
exp = v # to take care of cases where the numbers in original list are all separated by > 100
else:
exp = list(set(exp)) # to get rid of the duplicates had the input been [2, 8, 10, 11, 500, 502]
print exp