0

I have two lists in Python.

list1 = ['a','a','b','a','c','b','c','a','d','a','b']
list2 = ['1','2','21','12','1','32','11','12','21','3','31']

I have to group the similar elements in list1. The corresponding elements in list2 should also get grouped based on this. Output should be this:

list1 = [['a','a','a','a','a'],['b','b','b'],['c','c'],['d']]
list2 = [['1','2','12','12','3'],['21','32','31'],['1','11'],['21']]

What is the best way to do this?

2
  • Do you have to keep order of elements in the output lists? Commented Nov 2, 2015 at 12:45
  • There are many ways to do this. What trouble are you having with your way? Commented Nov 2, 2015 at 13:18

5 Answers 5

2

If you do not care about the order of elements in the first list, you may use defaultdict:

In [7]: from collections import defaultdict

In [8]: from itertools import izip

In [9]: res = defaultdict(list)

In [10]: for k, v in izip(list1, list2):
   ....:     res[k].append(v)
   ....:     

In [11]: print(res)
defaultdict(<type 'list'>, {'a': ['1', '2', '12', '12', '3'], 'c': ['1', '11'], 'b': ['21', '32', '31'], 'd': ['21']})

In [12]: res.items()
Out[12]: 
[('a', ['1', '2', '12', '12', '3']),
 ('c', ['1', '11']),
 ('b', ['21', '32', '31']),
 ('d', ['21'])]
Sign up to request clarification or add additional context in comments.

Comments

1

This code worked for me:

groups = list(set(list1))
list1_tmp, list2_tmp = [], []
for char in groups:
   list1_tmp.append([])
   list2_tmp.append([])

for i in range(len(list1)):
   list1_tmp[groups.index(list1[i])].append(list1[i])
   list2_tmp[groups.index(list1[i])].append(list2[i])

list1 = list1_tmp
list2 = list2_tmp

The output should be valid as well for any other similar input.

Comments

1

This code should do it:

final_list1 = []
final_list2 = []

for distinct in sorted(list(set(list1))):
    index = 0
    distinct_list1 = []
    distinct_list2 = []
    for element in list1:
        if element == distinct:
            distinct_list1.append(element)
            distinct_list2.append(list2[index])
        index += 1
    final_list1.append(distinct_list1)
    final_list2.append(distinct_list2)

list1 = final_list1
list2 = final_list2

This will give you exactly the output you asked for. If you don't really care about the output, there are probably better ways as @soon proposed.

Comments

1

Here's a (kind of ugly) implementation that would do the trick:

list1 = ['a','a','b','a','c','b','c','a','d','a','b']
list2 = ['1','2','21','12','1','32','11','12','21','3','31']

def transform(in_list, other_list):
    if len(in_list) != len(other_list):
        raise ValueError("Lists must have the sema length!")
    out_list = list()
    out_other_list = list()
    for i, c in enumerate(in_list):
        for inner_list, inner_other_list in zip(out_list, out_other_list):
            if c in inner_list:
                inner_list.append(c)
                inner_other_list.append(other_list[i])
                break
        else:
            out_list.append([c])
            out_other_list.append([other_list[i]])
    return out_list, out_other_list

print transform(list1, list2)

Comments

1

Though I personally like soon's answer,This one successfully retrieve your desired output.

lst= sorted(zip(list1,list2),key=lambda x:x[0])

intList=[]

initial=lst[0][0]
count=0

for index,value in enumerate(lst):
    if value[0]==initial:
        continue
    else:
        intList.append(lst[count:index])
        initial=value[0]
        count=index

finList1=[[a for a,b in innerList] for innerList in intList]
finList2=[[b for a,b in innerList] for innerList in intList]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.