I have a tuple as given below
JavaScript
x
44
44
1
all_combi= [
2
('a', 33.333333333333336),
3
('a', 38.333333333333336),
4
('a', 43.333333333333336),
5
('a', 48.333333333333336),
6
('a', 53.333333333333336),
7
('a', 58.333333333333336),
8
('a', 63.333333333333336),
9
('a', 68.33333333333334),
10
('a', 73.33333333333334),
11
('a', 78.33333333333334),
12
('a', 83.33333333333334),
13
('a', 88.33333333333334),
14
('a', 93.33333333333334),
15
('a', 98.33333333333334),
16
('b', 33.333333333333336),
17
('b', 38.333333333333336),
18
('b', 43.333333333333336),
19
('b', 48.333333333333336),
20
('b', 53.333333333333336),
21
('b', 58.333333333333336),
22
('b', 63.333333333333336),
23
('b', 68.33333333333334),
24
('b', 73.33333333333334),
25
('b', 78.33333333333334),
26
('b', 83.33333333333334),
27
('b', 88.33333333333334),
28
('b', 93.33333333333334),
29
('b', 98.33333333333334),
30
('c', 33.333333333333336),
31
('c', 38.333333333333336),
32
('c', 43.333333333333336),
33
('c', 48.333333333333336),
34
('c', 53.333333333333336),
35
('c', 58.333333333333336),
36
('c', 63.333333333333336),
37
('c', 68.33333333333334),
38
('c', 73.33333333333334),
39
('c', 78.33333333333334),
40
('c', 83.33333333333334),
41
('c', 88.33333333333334),
42
('c', 93.33333333333334),
43
('c', 98.33333333333334)]
44
I want to sort this tuple based on this list
JavaScript
1
2
1
instr_list. = ['a', 'b', 'c']
2
The sample of the expected output is given below
JavaScript
1
10
10
1
[[
2
('a', 33.333333333333336),
3
('b', 33.333333333333336),
4
('c', 33.333333333333336)
5
], [
6
[('a', 33.333333333333336),
7
('b', 38.333333333333336),
8
('c', 43.333333333333336)]
9
]]
10
I tried the following solution given at here to sort a tuple based on list. But it doesnt give the desired outcome. I tried using explicit loop but it doesnt work. Any help is appreciated…
JavaScript
1
15
15
1
def get_slab_list(all_combi, instr_list):
2
out_master_list = []
3
for i in range(len(instr_list)):
4
#k=0
5
out_list=[]
6
7
for j in all_combi:
8
if j[0] == instr_list[i]:
9
out_list.append(j[1])
10
11
out_master_list.append(out_list)
12
return out_master_list
13
14
sample = get_slab_list(all_combi, instr_list)
15
Advertisement
Answer
Here is solution you can try out, using sorted
+ groupby
JavaScript
1
10
10
1
from itertools import groupby
2
3
# if data is already sorted, you can avoid this step.
4
all_combi = sorted(all_combi, key=lambda x: x[1])
5
6
print(
7
[[i for i in v if i[0] in instr_list] # filter out only required keys
8
for _, v in groupby(all_combi, key=lambda x: x[1])]
9
)
10
JavaScript
1
8
1
[[('a', 33.333333333333336),
2
('b', 33.333333333333336),
3
('c', 33.333333333333336)],
4
[('a', 38.333333333333336),
5
('b', 38.333333333333336),
6
('c', 38.333333333333336)],
7
8