0
mylist = [10, 11, 12, 801, 802, 803,820, 2000, 2010, 2020]

I want it to be split into 3 sublists based on variations in values:

output should be:

sublist_1 = [10,11,12]
sublist_2 = [801,802,803,820]
sublist_3 = [2000,2010,2020]

The numerical distance between any two of sublists should be >30, e.g. the distance between sublist_1 and sublist_2 is 800-12 = 788. But the distance with any two neighbors in a sublist should be <20, e.g. in sublist_2, the maximum distance with any two neighours is 820-803 = 17.

  • Can you have a go at formalizing the logic? The logic as currently stated can give multiple formulations for a given list. – jpp Feb 07 '18 at 09:34
  • Ever hear about the little known problem called clustering? – Veltzer Doron Feb 07 '18 at 09:35
  • I googled "python group integers by close values" and that linked question came first. Please use your google-fu more carefully – Jean-François Fabre Feb 07 '18 at 09:38
  • I used not as good keyword as yours for google. I got very nice inspirations from the previous anwer from the similar question in the top. Thanks to you fantastic guys! – Yonghui Zeng Feb 07 '18 at 09:50
  • Please notice that the answer in https://stackoverflow.com/questions/10016802/python-group-a-list-of-integer-with-nearest-values doesn't apply to values with large variations, like I have here, from two digits to three digits values. You need to adjust the 'average' manually to suit specific needs. – Yonghui Zeng Feb 07 '18 at 10:03
  • @YonghuiZeng You are right i believe your question waas incorrectly closed so i reopened it – jamylak Feb 07 '18 at 15:06
  • could you please remove the [duplicate] tag? I'm eager to know the correct code for this. The previous answers are not working properly. – Yonghui Zeng Feb 08 '18 at 14:04
  • Please explain in your post why the method in the duplicate does not work. – Jongware Feb 08 '18 at 14:35
  • You're right. That answer works! – Yonghui Zeng Feb 08 '18 at 22:31

0 Answers0