I have got a List of tuples of tuples like below:
x = [
(('102', '393', 'abc'), 63),
(('102', '393', 'ack'), 8),
(('117', '393', 'bcx'), 57),
(('390', '393', 'wff'), 41),
(('393', '102', 'wer'), 40),
(('393', '102', 'wfv'), 78),
(('393', '117', 'iyy'), 7),
(('393', '448', 'wec'), 25),
]
and I am trying to extract the tuples wherein " (('102', '393', 'abc'), 63) and "(('102', '393', 'ack'), 8)," in a same small list
So the output should be
[
[ (('102', '393', 'abc'), 63), (('102', '393', 'ack'), 8)],
[ (('117', '393', 'bcx'), 57)],
[ (('390', '393', 'wff'), 41)],
[ (('393', '102', 'wer'), 40), (('393', '102', 'wfv'), 78)],
[ (('393', '117', 'iyy'), 7)],
[ (('393', '448', 'wec'), 25)]
]
I am trying to execute it in python with bubble_sort. I tried this
for i in range(1, len(x)):
for j in range(0, len(x)):
if x[j][0] == x[j + 1][0] and x[j][1] == x[j + 1][1]:
pass
However, it's not working.
Any help in this regard will be appreciated.
Using itertools.groupby
( doc ):
x = [
(('102', '393', 'abc'), 63),
(('102', '393', 'ack'), 8),
(('117', '393', 'bcx'), 57),
(('390', '393', 'wff'), 41),
(('393', '102', 'wer'), 40),
(('393', '102', 'wfv'), 78),
(('393', '117', 'iyy'), 7),
(('393', '448', 'wec'), 25),
]
from itertools import groupby
out = [[*g] for _, g in groupby(x, lambda k: (k[0][0], k[0][1]))]
from pprint import pprint
pprint(out)
Prints:
[[(('102', '393', 'abc'), 63), (('102', '393', 'ack'), 8)],
[(('117', '393', 'bcx'), 57)],
[(('390', '393', 'wff'), 41)],
[(('393', '102', 'wer'), 40), (('393', '102', 'wfv'), 78)],
[(('393', '117', 'iyy'), 7)],
[(('393', '448', 'wec'), 25)]]
you can try by using a defaultdict/dict:
from pprint import pprint
from collections import defaultdict
x = [
(('102', '393', 'abc'), 63),
(('102', '393', 'ack'), 8),
(('117', '393', 'bcx'), 57),
(('390', '393', 'wff'), 41),
(('393', '102', 'wer'), 40),
(('393', '102', 'wfv'), 78),
(('393', '117', 'iyy'), 7),
(('393', '448', 'wec'), 25),
]
val = defaultdict(list)
for item in x:
val[item[0][0], item[0][1]].append(item)
pprint(list(val.values()))
output:
[[(('102', '393', 'abc'), 63), (('102', '393', 'ack'), 8)],
[(('117', '393', 'bcx'), 57)],
[(('390', '393', 'wff'), 41)],
[(('393', '102', 'wer'), 40), (('393', '102', 'wfv'), 78)],
[(('393', '117', 'iyy'), 7)],
[(('393', '448', 'wec'), 25)]]
if you want to take only the second element from each list item, after the above processing :
pprint([[e[1] for e in i] for i in val.values()])
output:
[[63, 8], [57], [41], [40, 78], [7], [25]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.