-1

I have a multiple lists like this,

[100,200,100,1,ASD1]
[200,350,150,2,ASD2]
[300,400,120,3,ASD1]
[400,500,130,4,ASD2]

And I want to join the lists based on the last value of the list.

[[100,200,100,1,ASD1],[300,400,120,3,ASD1]]
[[200,350,150,2,ASD2],[400,500,130,4,ASD2]]

How to join the lists like this.If anyone knows pls help me.

Aishwarya
  • 69
  • 5

3 Answers3

3

Using a defaultdict of lists:

from collections import defaultdict

data = [[100,200,100,1,'ASD1'],
        [200,350,150,2,'ASD2'],
        [300,400,120,3,'ASD1'],
        [400,500,130,4,'ASD2']]

dd = defaultdict(list)
for item in data:
    dd[item[-1]].append(item)

res = list(dd.values())

print(res)
# [[[100, 200, 100, 1, 'ASD1'], [300, 400, 120, 3, 'ASD1']],
#  [[200, 350, 150, 2, 'ASD2'], [400, 500, 130, 4, 'ASD2']]]
jpp
  • 159,742
  • 34
  • 281
  • 339
  • 2
    Instead of posting code for the problem, it's much better, if you share the pesudo code and let the person themselves, curate a solution to the problem. – taurus05 Jan 30 '19 at 05:06
2

You can do as follows:

  1. Extract the last value of all the lists and make a set out of those values.
  2. Now, as you have all the possible values, that the last element in the list can take, you know, the length of the new list.
  3. Now, iterate over the original list and append them to the list with that particular element as the key.
  4. DefaultDict will be really handy for you in this case. Click Here
taurus05
  • 2,491
  • 15
  • 28
0
mydict = {}

data = [[100,200,100,1,'ASD1'],
    [200,350,150,2,'ASD2'],
    [300,400,120,3,'ASD1'],
    [400,500,130,4,'ASD2']]

for i in data:
   if i[-1] in mydict:
      mydict[i[-1]].append(i)
   else:
      mydict[i[-1]] = [i]
mydict.values()
#for python 3
#list(mydict.values())

#OUTPUT:[[[100, 200, 100, 1, 'ASD1'], [300, 400, 120, 3, 'ASD1']], [[200, 350, 
 #150,2,'ASD2'], [400, 500, 130, 4, 'ASD2']]]
vinodsesetti
  • 368
  • 2
  • 6