Home > Mobile >  how to insert into sublists the correct values from a list of lists
how to insert into sublists the correct values from a list of lists

Time:05-05

I have a list of lists of this kind:

[
[[1, 26, 0.6], [2, 0.17, 0.63], [3, 1.4, 0.65]],
[[1, 834, 0.61], [2, 344, 0.64], [3, 30, 0.7], [4, 31, 0.65]]
]

I'd like to create another list of lists in which I save in each sublist the third element of the sublists written before (in the same sublist I would like to have all the third elements of the lists that have the same first element).

[[0.6,0.61],
[0.63,0.64],
[0.65,0.7],
[0.65]
] 

Suggestions? Thank you!

CodePudding user response:

Okay, this is a simple case. But obviously, need experienced coding skills. This my the most basic solution, you can double-check.

l = [
[[1, 26, 0.6], [2, 0.17, 0.63], [3, 1.4, 0.65]],
[[1, 834, 0.61], [2, 344, 0.64], [3, 30, 0.7], [4, 31, 0.65]]
]
dic = {}
for items in l:
  for item in items:
        # Initialize a list with the first last-element for the value key
        # If it does not exist. Else, add  it into the list of the key item[0]
    if item[0] not in dic.keys():
      dic[item[0]] = [item[-1]]
    else:
      dic[item[0]].append(item[-1])
    
ans = [ v for k,v in dic.items() ]

print(ans)

Note I have tried to make the code as usable as I can. This code works well when you have more than just 2 sub-list in the l variables. I can say it will work for the input like this also

l = [
[[1, 26, 0.6], [2, 0.17, 0.63], [3, 1.4, 0.65]],
[[1, 834, 0.61], [2, 344, 0.64], [3, 30, 0.7], [4, 31, 0.65]],
[[3,2,1],[4,4,4]]
]

CodePudding user response:

How about using an intermediate dictionary?

LOL = [
    [[1, 26, 0.6], [2, 0.17, 0.63], [3, 1.4, 0.65]],
    [[1, 834, 0.61], [2, 344, 0.64], [3, 30, 0.7], [4, 31, 0.65]]
]

d = dict()

for e in LOL:
    for e_ in e:
        d.setdefault(e_[0], []).append(e_[-1])

print(list(d.values()))

Output:

[[0.6, 0.61], [0.63, 0.64], [0.65, 0.7], [0.65]]
  • Related