我有一个列表编号说,
[1,2,3,6,8,9,10,11]
首先,我想得到列表中数字(n, n+1)
之间差异(步长)的总和。
其次,如果一组连续数字之间的差异为1,则将它们放在一个列表中,即本例中有两个这样的列表,
[1,2,3]
[8,9,10,11]
然后将其余的数字放在另一个列表中,即示例中只有一个这样的列表,
[6]
。
第三,从顺序列表中获取具有最大/最小尺寸的列表,例如[1,2,3]
,[8,9,10,11]
在此示例中,最大列表为,
[8,9,10,11]
min list is
[1,2,3]
。
实施此方法的最佳方式是什么?
答案 0 :(得分:4)
首先,我想得到两者之间的差异(步长)之和 列表中的数字
(n, n+1)
。
对列表中元素的连续差异使用sum
:
>>> sum(lst[i] - x for i, x in enumerate(lst[:-1], start=1))
10
其次,如果一组连续数字之间的差异为1,则将它们放入列表中,即有两个这样的列表 这个例子,然后将其余的数字放在另一个列表中,即 示例中只有一个这样的列表,
itertools.groupby
通过对引用itertools.count
对象上每个元素的差异进行分组来实现此目的:
>>> from itertools import groupby, count
>>> c = count()
>>> result = [list(g) for i, g in groupby(lst, key=lambda x: x-next(c))]
>>> result
[[1, 2, 3, 4], [6], [8, 9, 10, 11]]
第三,从上面获取具有最大/最小尺寸的列表
max
和min
键功能为sum
:
>>> max(result, key=sum)
[8, 9, 10, 11]
>>> min(result, key=sum)
[6] #??? shouldn't this be [6]
答案 1 :(得分:1)
我想知道你是否已经得到了答案(假设你的答案中缺少4个),这是我天真地试图做出的第一件事。 (那和/或它看起来像一个家庭作业问题)
>>> a=[1,2,3,4,6,8,9,10,11]
>>> sum([a[x+1] - a[x] for x in range(len(a)-1)])
10
>>> [a[x] for x in range(len(a)-1) if abs(a[x] - a[x+1]) ==1]
[1, 2, 3, 8, 9, 10]
或者,尝试:
a=[1,2,3,6,8,9,10,11]
sets = []
cur_set = set()
total_diff = 0
for index in range(len(a)-1):
total_diff += a[index +1] - a[index]
if a[index +1] - a[index] == 1:
cur_set = cur_set | set([ a[index +1], a[index]])
else:
if len(cur_set) > 0:
sets.append(cur_set)
cur_set = set()
if len(cur_set) > 0:
sets.append(cur_set)
all_seq_nos = set()
for seq_set in sets:
all_seq_nos = all_seq_nos | seq_set
non_seq_set = set(a) - all_seq_nos
print("Sum of differences is {0:d}".format(total_diff))
print("sets of sequential numbers are :")
for seq_set in sets:
print(sorted(list(seq_set)))
print("set of non-sequential numbers is :")
print(sorted(list(non_seq_set)))
big_set=max(sets, key=sum)
sml_set=min(sets, key=sum)
print ("Biggest set of sequential numbers is :")
print (sorted(list(big_set)))
print ("Smallest set of sequential numbers is :")
print (sorted(list(sml_set)))
哪个会产生输出:
Sum of differences is 10
sets of sequential numbers are :
[1, 2, 3]
[8, 9, 10, 11]
set of non-sequential numbers is :
[6]
Biggest set of sequential numbers is :
[8, 9, 10, 11]
Smallest set of sequential numbers is :
[1, 2, 3]
希望所有人都有所帮助; - )