Python_grouping multidimensional list - python

I have an example multidimensional list:
example_list=[
["a","b","c", 2,4,5,7],
["e","f","g",0,0,1,5],
["e","f","g", 1,4,5,7],
["a","b","c", 3,2,5,7]
]
How is it possible to put them in groups like this:
out_list=[
[["a","b","c", 2,4,5,7],
["a","b","c",3,2,5,7]
],
[["e","f","g", 0,0,1,5],
["e","f","g", 1,4,5,7]
]
]
I have tried this:
example_list=[["a","b","c", 2,4,5,7],["e","f","g", 0,0,1,5],["e","f","g",1,4,5,7],["a","b","c", 3,2,5,7]]
unique=[]
index=0
for i in range(len(example_list)):
newlist=[]
if example_list[i][:3]==example_list[index][:3]:
newlist.append(example_list[i])
index=index+1
unique.append(newlist)
print unique
My results is this:
[[['a', 'b', 'c', 2, 4, 5, 7]], [['e', 'f', 'g',0, 0, 1, 5]], [['e', 'f', 'g', 1, 4, 5, 7]], [['a', 'b', 'c', 3, 2, 5,7]]]
I could not figure it out.

If the grouping is decided by the first three elements in each list following code will do what you're asking for:
from collections import defaultdict
example_list=[["a","b","c", 2,4,5,7],["e","f","g",0,0,1,5],["e","f","g", 1,4,5,7],["a","b","c", 3,2,5,7]]
d = defaultdict(list)
for l in example_list:
d[tuple(l[:3])].append(l)
print d.values() # [[['a', 'b', 'c', 2, 4, 5, 7], ['a', 'b', 'c', 3, 2, 5, 7]], ...]
This will use defaultdict to generate a dictionary where keys are the first three elements and values are list of lists which start with those elements.

First sort the list simply using sorted(), providing a lambda function as key.
>>> a = sorted(example_list, key=lambda x:x[:3])
[['a', 'b', 'c', 2, 4, 5, 7], ['a', 'b', 'c', 3, 2, 5, 7], ['e', 'f', 'g', 0, 0, 1, 5], ['e', 'f', 'g', 1, 4, 5, 7]]
And then use itertools.groupby() on the sorted list:
>>> [list(v) for k, v in groupby(a, lambda x:x[:3])]
[
[['a', 'b', 'c', 2, 4, 5, 7], ['a', 'b', 'c', 3, 2, 5, 7]],
[['e', 'f', 'g', 0, 0, 1, 5], ['e', 'f', 'g', 1, 4, 5, 7]]
]

Related

How can I rotate a list right and left?

I have been trying to rotate a list left and right in python
def rotate(l, r):
return l[r:] + l[:r]
l = eval(input())
r = int(input())
print(rotate(l, r))
but if i give input list as ['A','B','C','D',1,2,3,4,5] and r = -34 I'm getting output as
['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
but actual output is this :
['C', 'D', 1, 2, 3, 4, 5, 'A', 'B']
Can anyone tell how can I do it?
First you could use print() and test it for different values
def rotate(l, r):
return l[r:] + l[:r]
l = ['A','B','C','D',1,2,3,4,5]
print('len(l):', len(l))
for r in range(0, -34, -1):
print(f"{r:3}", rotate(l, r))
And you see
len(l): 9
0 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-1 [5, 'A', 'B', 'C', 'D', 1, 2, 3, 4]
-2 [4, 5, 'A', 'B', 'C', 'D', 1, 2, 3]
-3 [3, 4, 5, 'A', 'B', 'C', 'D', 1, 2]
-4 [2, 3, 4, 5, 'A', 'B', 'C', 'D', 1]
-5 [1, 2, 3, 4, 5, 'A', 'B', 'C', 'D']
-6 ['D', 1, 2, 3, 4, 5, 'A', 'B', 'C']
-7 ['C', 'D', 1, 2, 3, 4, 5, 'A', 'B']
-8 ['B', 'C', 'D', 1, 2, 3, 4, 5, 'A']
-9 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-10 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-11 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-12 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-13 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-14 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-15 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-16 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-17 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-18 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-19 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-20 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-21 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-22 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-23 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-24 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-25 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-26 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-27 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-28 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-29 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-30 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-31 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-32 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-33 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
When -r is bigger then len(r) then it doesn't work as you would expect.
It gets empty list + full list or full list + empty list
The same problem is with +34 and -34.
Because you get the same list for r=len(l), r=len(l)*2, ...r=len(l)*n so you would use modulo (r % len(l)) to have value smaller then len(l) and get what you need.
def rotate(l, r):
r = r % len(l)
return l[r:] + l[:r]
l = ['A','B','C','D',1,2,3,4,5]
print('len(l):', len(l))
for r in range(0, -34, -1):
print(f"{r:3}", rotate(l, r))
Result:
len(l): 9
0 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-1 [5, 'A', 'B', 'C', 'D', 1, 2, 3, 4]
-2 [4, 5, 'A', 'B', 'C', 'D', 1, 2, 3]
-3 [3, 4, 5, 'A', 'B', 'C', 'D', 1, 2]
-4 [2, 3, 4, 5, 'A', 'B', 'C', 'D', 1]
-5 [1, 2, 3, 4, 5, 'A', 'B', 'C', 'D']
-6 ['D', 1, 2, 3, 4, 5, 'A', 'B', 'C']
-7 ['C', 'D', 1, 2, 3, 4, 5, 'A', 'B']
-8 ['B', 'C', 'D', 1, 2, 3, 4, 5, 'A']
-9 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-10 [5, 'A', 'B', 'C', 'D', 1, 2, 3, 4]
-11 [4, 5, 'A', 'B', 'C', 'D', 1, 2, 3]
-12 [3, 4, 5, 'A', 'B', 'C', 'D', 1, 2]
-13 [2, 3, 4, 5, 'A', 'B', 'C', 'D', 1]
-14 [1, 2, 3, 4, 5, 'A', 'B', 'C', 'D']
-15 ['D', 1, 2, 3, 4, 5, 'A', 'B', 'C']
-16 ['C', 'D', 1, 2, 3, 4, 5, 'A', 'B']
-17 ['B', 'C', 'D', 1, 2, 3, 4, 5, 'A']
-18 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-19 [5, 'A', 'B', 'C', 'D', 1, 2, 3, 4]
-20 [4, 5, 'A', 'B', 'C', 'D', 1, 2, 3]
-21 [3, 4, 5, 'A', 'B', 'C', 'D', 1, 2]
-22 [2, 3, 4, 5, 'A', 'B', 'C', 'D', 1]
-23 [1, 2, 3, 4, 5, 'A', 'B', 'C', 'D']
-24 ['D', 1, 2, 3, 4, 5, 'A', 'B', 'C']
-25 ['C', 'D', 1, 2, 3, 4, 5, 'A', 'B']
-26 ['B', 'C', 'D', 1, 2, 3, 4, 5, 'A']
-27 ['A', 'B', 'C', 'D', 1, 2, 3, 4, 5]
-28 [5, 'A', 'B', 'C', 'D', 1, 2, 3, 4]
-29 [4, 5, 'A', 'B', 'C', 'D', 1, 2, 3]
-30 [3, 4, 5, 'A', 'B', 'C', 'D', 1, 2]
-31 [2, 3, 4, 5, 'A', 'B', 'C', 'D', 1]
-32 [1, 2, 3, 4, 5, 'A', 'B', 'C', 'D']
-33 ['D', 1, 2, 3, 4, 5, 'A', 'B', 'C']
BTW:
Without modulo you would have to use for-loops with [1:], [:1] or [-1:],[:-1] - but it need many moves - so it may need more time and memory (but for small list it is not visible).
def rotate(l, r):
if r >= 0:
for _ in range(0, r, 1):
l = l[1:] + l[:1]
else:
for _ in range(0, r, -1):
l = l[-1:] + l[:-1]
return l
l = ['A','B','C','D',1,2,3,4,5]
print('len(l):', len(l))
#for r in range(0, -34, -1):
# print(f"{r:3}", rotate(l, r))
for r in range(0, 34, 1):
print(f"{r:3}", rotate(l, r))
The same with one for-loop
def rotate(l, r):
if r >= 0:
s = 1
else:
s = -1
for _ in range(0, r, s):
l = l[s:] + l[:s]
return l
If r can be bigger than the list you need to add the modulo operater as #tim-roberts mentioned:
def rotate(l, r):
r = r % len(l)
return l[r:] + l[:r]
Outputs
l = [1,2,3]
print(rotate(l,0))
[1, 2, 3]
print(rotate(l,1))
[2, 3, 1]
print(rotate(l,-1))
[3, 1, 2]
print(rotate(l,4))
[2, 3, 1]
print(rotate(l,-4))
[3, 1, 2]
(personally I'd also turn around the rotation direction, using e.g. -r)

Merging 2 arrays in Python

I have 2 arrays:
first_arr = ['A', 'B', 'C', 'D', 'E', 'F']
second_arr = [1, 2, 3, 4, 5, 6]
And I'd like to unite them to an array or a list like this:
third_arr = [['A',1], ['B',2], ['C',3], ['D',4], ['E',5], ['F',6]]
or my_list = [['A',1], ['B',2], ['C',3], ['D',4], ['E',5], ['F',6]]
What is the easiest way to do it?
You can use zip() to merge the arrays...
first_arr = ['A', 'B', 'C', 'D', 'E', 'F']
second_arr = [1, 2, 3, 4, 5, 6]
third_arr = list(zip(first_arr, second_arr))
print(third_arr)
Which results in...
[('A', 1), ('B', 2), ('C', 3), ('D', 4), ('E', 5), ('F', 6)]
There is no difference between ('A',1) and ['A',1] in most cases. However, if you want to, you can change then from tuples to lists by assigning third_arr to the following...
...
third_arr = [list(t) for t in zip(first_arr, second_arr)]
print(third_arr)
Which results in...
[['A', 1], ['B', 2], ['C', 3], ['D', 4], ['E', 5], ['F', 6]]
Starting with the two lists, you can create a third list joining the elements of the two lists using the method .append() in a for loop:
first_arr = ['A', 'B', 'C', 'D', 'E', 'F']
second_arr = [1, 2, 3, 4, 5, 6]
my_list = []
for i in range(0,len(first_arr)):
my_list.append([first_arr[i],second_arr[i]])
my_list
[['A', 1], ['B', 2], ['C', 3], ['D', 4], ['E', 5], ['F', 6]]

Create all combinations of two sets of lists in Python

I am trying to create all combinations of two sets of lists using as follows:
x = [[1,2,3],[4,5,6]]
y = [['a','b','c'],['d','e','f']]
combos = [[1,2,3,'a','b','c'],[4,5,6,'d','e','f'],[4,5,6,'a','b','c'],[4,5,6,'d','e','f']]
I think itertools may be of some help but not sure how. Thanks
You can use product and chain:
from itertools import product, chain
[list(chain(*i)) for i in product(x, y)]
#[[1, 2, 3, 'a', 'b', 'c'],
# [1, 2, 3, 'd', 'e', 'f'],
# [4, 5, 6, 'a', 'b', 'c'],
# [4, 5, 6, 'd', 'e', 'f']]
Or you can use a list comprehension:
[i + j for i in x for j in y]
#[[1, 2, 3, 'a', 'b', 'c'],
# [1, 2, 3, 'd', 'e', 'f'],
# [4, 5, 6, 'a', 'b', 'c'],
# [4, 5, 6, 'd', 'e', 'f']]

How to flatten the list matrix (list of lists) in order of index?

list_data = [['a', 'b', 'c', 'd'],
['hello', 'mellow', 'fellow', 'jello'],
[2, 3, 6, 8]]
flattened = []
for data in list_data:
for x in data:
flattened.append(x)
print(flatenned)
gives me:
['a', 'b', 'c', 'd', 'hello', 'mellow', 'fellow', 'jello', 2, 3, 6, 8]
How, can I rather flatten this lits to (below) in a most simple way:
['a', 'hello', 2, 'b', 'mellow', 3, 'c', 'fellow', 6, 'd', 'jello', 8]
and to dictionary:
['a': ['hello' 2], 'b': ['mellow', 3], 'c': ['fellow', 6], 'd': ['jello', 8]]
Explanation of the process would be helpful.
You can use zip to transpose the matrix:
[y for x in zip(*list_data) for y in x]
# ['a', 'hello', 2, 'b', 'mellow', 3, 'c', 'fellow', 6, 'd', 'jello', 8]
To get the dictionary:
dict(zip(list_data[0], zip(*list_data[1:])))
# {'a': ('hello', 2), 'b': ('mellow', 3), 'c': ('fellow', 6), 'd': ('jello', 8)}
Description:
Dictionary is reported as keys and values, d[k,v].
so, first part list_data[0] picks keys from the first index (0) of every list, and the latter part zip(*list_data[1:]) adds the remaining elements of the list as the values for that key.
For flattening the list, you may use itertools.chain with zip as:
>>> from itertools import chain
>>> list(chain(*zip(*list_data)))
['a', 'hello', 2, 'b', 'mellow', 3, 'c', 'fellow', 6, 'd', 'jello', 8]
For mapping the values to desired dict, you may use zip with dictionary comprehension expression as:
>>> {i: [j, k] for i, j, k in zip(*list_data)}
{'a': ['hello', 2], 'c': ['fellow', 6], 'b': ['mellow', 3], 'd': ['jello', 8]}

python: combine lists of lists for SQLITE table

I need to combine 3 lists into one list so that I can insert it smoothly into sqlite table.
list1= [[a1,b1,c1],[a2,b2,c2]]
list2= [[d1,e1,f1],[d2,e2,f2]]
Output should look like:
combined_list = [[a1,b1,c1,d1,e1,f1],[a2,b2,c2,d2,e2,f2]]
I tried sum list1 + list2 but both didn't work as this output.
You can try this:
from operator import add
a=[[1, 2, 3], [4, 5, 6]]
b=[['a', 'b', 'c'], ['d', 'e', 'f']]
print a + b
print map(add, a, b)
Output:
[[1, 2, 3], [4, 5, 6], ['a', 'b', 'c'], ['d', 'e', 'f']]
[[1, 2, 3, 'a', 'b', 'c'], [4, 5, 6, 'd', 'e', 'f']]
Edit:
To add more than two arrays:
u=[[]]*lists[0].__len__()
for x in lists:
u=map(add, u, x)

Categories