how to unpack a nested list in Python - list

How to unpack a list, which is nested inside another list.
Practically to transform this:
l=['aa','bb',['ccc','ddd'],'ee']
to
l=['aa','bb','ccc','ddd','ee']

See this thread and e. g. the solution of elqott
>>> from compiler.ast import flatten
>>> l = ['1','2',['3','4'],'5']
>>> flatten(l)
Following your edit
['1', '2', '3', '4', '5']
>>> l = ['aa','bb',['ccc','ddd'],'ee']
>>> flatten(l)
['aa', 'bb', 'ccc', 'ddd', 'ee']

Related

Transform list to the dictionary

I have a list with a strings
['scene-task-v001-user', 'scene-task-v002-user', 'scene-explo-v001-user', 'scene-train-v001-user', 'scene-train-v002-user']
strings created by regular expression
'(?P<scene>\w+)-(?P<task>\w+)-v(?P<ver>\d{3,})-(?P<user>\w+)'
I need to create dictionary where key its a task group and values contain all ver groups with the same task
{'task': ['001', '002'], 'explo': ['001'], 'train': ['001', '002']}
How to do it?
Thanks!
First of all, ('t-1', 't-2', 's-1', 'z-1', 'z-2') is a tuple, not a list. In addition, {'t': {'1', '2'}, 's': {'1'}, 'z': {'1', '2'}} is wrong expression, a form of the values would be a list here, not {}. I corrected this issue in my codes below.
Instead of using regular expression, you can loop the list and split by '-' inside the loop to get keys and values, as follows:
from collections import defaultdict
l = ('t-1', 't-2', 's-1', 'z-1', 'z-2')
d = defaultdict(list)
for item in l:
key, val = item.split('-')
d[key].append(val)
print(d) # defaultdict(<class 'list'>, {'t': ['1', '2'], 's': ['1'], 'z': ['1', '2']})
print(d['t']) # ['1', '2']
Using regular expressions to get keys and values for a dictionary:
from collections import defaultdict
import re
l = ('t-1', 't-2', 's-1', 'z-1', 'z-2')
d = defaultdict(list)
for item in l:
key_patten = re.compile('\w-')
val_patten = re.compile('-\w')
key = key_patten.search(item).group().replace('-', '')
val = val_patten.search(item).group().replace('-', '')
d[key].append(val)
print(d) # defaultdict(<class 'list'>, {'t': ['1', '2'], 's': ['1'], 'z': ['1', '2']})
print(d['t']) # ['1', '2']

Creating a dictionary from list of lists

I have a list of lists in the following format:
[['a'],['1'],['2'],['3'], ['b'],['4'],['5'],['6']]
My desired output is:
[['a', '1'], ['a', '2'], ['a','3'],['b', '4'],['b', '5'],['b', '6']]
or even better would be:
{'a':['1','2','3'], 'b':['4','5','6']}
Essentially, the "number values" are never the same size (think that a could include 1 2 and 3, and b could include 4 5 6 7 and 8, etc)
What would be the easiest way of doing this? Using regex?
Thanks
You can use a for loop and check if the element is a digit or not:
d = {}
for i in lst:
if not i[0].isdigit(): # Check if element is a digit. If not, add a key with the current value of i[0]
d[i[0]] = []
current = i[0]
else:
d[current].append(i[0])
Output:
>>> d
{'a': ['1', '2', '3'], 'b': ['4', '5', '6']}
This is assuming everything in the list is a string

Generating permutations of a given length - Python

I want to generate a list of permutations over a given alphabet of length n.
For example, if n = 3 and the alphabet includes {A,B}, output should be: AAA,AAB,ABA,BAA,ABB,BAB,BBA,BBB
I'm guessing from the desired output that you want to generate the cartesian product of an alphabet with itself repeated n times rather than a list of permutations. This admittedly tricky wrapper of itertools.product() will do the job just fine:
>>> import itertools
>>> def nprod(x, n):
... args = 'x' + (n-1)*', x'
... return [''.join(z) for z in eval('itertools.product(%s)' % args)]
...
>>> nprod('AB', 3)
['AAA', 'AAB', 'ABA', 'ABB', 'BAA', 'BAB', 'BBA', 'BBB']
>>> nprod(['1', '2', '3'], 2)
['11', '12', '13', '21', '22', '23', '31', '32', '33']
EDIT: Oh, silly me!!! I didn't notice in the documentation the optional repeat keyword argument :D
>>> [''.join(x) for x in itertools.product('AB', repeat=3)]
['AAA', 'AAB', 'ABA', 'ABB', 'BAA', 'BAB', 'BBA', 'BBB']
>>>> [''.join(x) for x in itertools.product(['1', '2', '3'], repeat=2)]
['11', '12', '13', '21', '22', '23', '31', '32', '33']

Dictionary Key Error

I am trying to construct a dictionary with values from a csv file.Say 10 columns there and i want to set the first column as key and the remaining as Values.
If setting as a for loop the dictionary has to have only one value. Kindly Suggest me a way.
import csv
import numpy
aname = {}
#loading the file in numpy
result=numpy.array(list(csv.reader(open('somefile',"rb"),delimiter=','))).astype('string')
#devolop a dict\
r = {aname[rows[0]]: rows[1:] for rows in result}
print r[0]
Error as follows.
r = {aname[rows[0]]: rows[1:] for rows in result}
KeyError: '2a9ac84c-3315-5576-4dfd-8bc34072360d|11937055'
I'm not entirely sure what you mean to do here, but does this help:
>>> result = [[1, 'a', 'b'], [2, 'c', 'd']]
>>> dict([(row[0], row[1:]) for row in result])
{1: ['a', 'b'], 2: ['c', 'd']}

Find overlapping List in 2 Lists of Lists

I would like to find overlapping lists in two lists of lists.
ListLeft = [['A', 'B', 'C'], ['1', '2', '3', '4'], ['x', 'y'], ['one', 'two', 'three']]
ListRight = [['h', 'i', 'j'], ['A', 'B', 'C'], ['1', '2', '3', '4'], ['5', '6', '7'], ['x', 'y']]
Someone might have a solution to find/print content of overlapping lists and lists which are not in both lists
Maybe this is possible without importing modules.
This can be simply achieved by using loop:
overlap = []
for ll in ListLeft:
for lr in ListRight:
if ll == lr:
overlap.append(ll)
break
print overlap
>>> [['A', 'B', 'C'], ['1', '2', '3', '4'], ['x', 'y']]