how to create a list from multiple sublists [duplicate] - python

This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed 6 months ago.
I have a list with the following structure:
list = ['a', ['b','c','d'], ['e','f']]
how can I create the following structure from it:
list = ['a','b','c','d','e','f']

list = ['a', ['b','c','d'], ['e','f']]
lst = [element for nested_list in list for element in nested_list]
print(lst)
Result:
['a', 'b', 'c', 'd', 'e', 'f']

This supports nested list too.
res = []
def parse(li):
if isinstance(li, list):
for a in li:
parse(a)
return
res.append(li)
my_List = ['a', ['b','c','d', ['g', 'h']], ['e','f']]
parse(my_List)
print(res)
Output:
['a', 'b', 'c', 'd', 'g', 'h', 'e', 'f']

Related

why does my for loop keep on removing the append element [duplicate]

This question already has answers here:
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed 3 months ago.
so I am trying to create a list that have different list as it element
the for loop bellow will extend an element to the bag then append it to the list bag and finally remove the extended element to repeat the cyclec
the bag contains these elements ['B', 'D']
and the rf contains these elements ['C', 'A', 'G', 'E']
list_bag = []
for i in range(len(rf)) :
bag.extend(rf[i])
a= bag
list_bag.append(a)
bag.pop()
print(list_bag)
the out put I am trying to archive is this :
[['B', 'D','A'], ['B', 'D','E'], ['B', 'D','F'], ['B', 'D','C']]
but the code keep on giving me this
[['B', 'D'], ['B', 'D'], ['B', 'D'], ['B', 'D']]
any suggestion ?
You can accomplish what you want with a list comprehension.
list_bag = [bag + [item] for item in rf]

Flatten a list with sublists and strings [duplicate]

This question already has answers here:
Flatten an irregular (arbitrarily nested) list of lists
(51 answers)
How do I make a flat list out of a list of lists?
(34 answers)
Closed 1 year ago.
How can I flatten a list of lists into a list?
For ex,:
Input_List = [['a', 'b'],'c','d',['e', 'f']]
Expectation:
Final_List = ['a','b','c','d','e','f']
You will need to check the type of each list item to determine if it is merely a value to output or a sublist to expand.
Using a list comprehension:
Input_List = [['a', 'b'],'c','d',['e', 'f']]
Final_List = [v for i in Input_List for v in (i if isinstance(i,list) else [i])]
print(Final_List)
['a', 'b', 'c', 'd', 'e', 'f']
Or using an iterative loop:
Final_List = []
for item in Input_List:
if isinstance(item,list): Final_List.extend(item)
else: Final_List.append(item)
print(Final_List)
['a', 'b', 'c', 'd', 'e', 'f']
Or using a recursive function if you need to flatten all levels of nested lists:
def flat(A):
return [v for i in A for v in flat(i)] if isinstance(A,list) else [A]
Input_List = [['a', 'b'],'c','d',['e2', 'f3',['x','y']]]
Final_List = flat(Input_List)
print(Final_List)
['a', 'b', 'c', 'd', 'e2', 'f3', 'x', 'y']
this working only for -> multdimensional at the same dimension
from itertools import chain
ini_list = [[1, 2, 3],
[3, 6, 7],
[7, 5, 4]]
print ("initial list ", str(ini_list))
flatten_list = list(chain.from_iterable(ini_list))
print ("final_result", str(flatten_list))
If some arrays isn't nested - then
def flatten(something):
if isinstance(something, (list, tuple, set, range)):
for sub in something:
yield from flatten(sub)
else:
yield something
test = flatten(ini_list)
list(test)

How to dynamically unpack a list as you create? [duplicate]

This question already has answers here:
Unpack list into middle of a tuple
(3 answers)
Closed 4 years ago.
How would I create a list element from function call?
Not sure if this is possible, but I've tried to create a list element from a function when i create the list as i'm not sure of the elements up until runtime
So I have tried this:
>>>> def make_list_element():
return 'd, e'
If i then try to create a list and call the function at the same time :
>>>> a = ['a', 'b', 'c', make_list_element().split(", ")]
And I get:
>>> a
>>> ['a', 'b', 'c', ['d', 'e']]
How could I achieve this:
>>> a
>>> ['a', 'b', 'c', 'd', 'e']
Preferably in the same statement as I create the list.
Many thanks
In Python3, you can simply unpack the returned list like so:
a = ['a', 'b', 'c', *make_list_element().split(", ") ]
If you're on Python2, you will have to concatenate or extend the list:
a = ['a', 'b', 'c'] + make_list_element().split(", ")
or
a = ['a', 'b', 'c']
a.extend(make_list_element().split(", "))

How to combine every element of a list to the other list [duplicate]

This question already has answers here:
How to get the cartesian product of multiple lists
(17 answers)
Closed 5 years ago.
Suppose there are two lists:
['a', 'b', 'c'], ['d', 'e', 'f']
what I want is:
'ad','ae','af','bd','be','bf','cd','ce','cf'
first_list = ['a', 'b', 'c']
second_list = ['d', 'e', 'f']
combined_list = []
for i in first_list:
for j in second_list:
combined_list.append(i + j)
print(combined_list)
my question is if there are not only two lists, how to improve the code?
for example,
first_list = ['a', 'b', 'c']
second_list = ['d', 'e', 'f']
third_list = ['g','h','q']
print ['adg','adh','adq','aeg','aeh',.......]
guys,are there any generalizable ways to show n lists..I mean what if there are more than three lists?
This is called a cartesian product.
import itertools
first_list = ['a', 'b', 'c']
second_list = ['d', 'e', 'f']
third_list = ['g','h','q']
lists = [first_list, second_list, third_list]
cartesian_product = [''.join(x) for x in itertools.product(*lists)]
print(cartesian_product)
Output:
['adg', 'adh', 'adq', 'aeg', 'aeh', 'aeq', 'afg', 'afh', 'afq',
'bdg', 'bdh', 'bdq', 'beg', 'beh', 'beq', 'bfg', 'bfh', 'bfq',
'cdg', 'cdh', 'cdq', 'ceg', 'ceh', 'ceq', 'cfg', 'cfh', 'cfq']
You can try it online, here.
Here's an example implementation of a cartesian production function, which you can try out here.
def cartesian_product(*lists):
if not lists: # base case
return [[]]
else:
this_list = lists[0]
remaining_lists = lists[1:]
return [
[x] + p
for x in this_list
for p in cartesian_product(*remaining_lists)
]
I haven't tested this but this should work.
first_list = ['a', 'b', 'c']
second_list = ['d', 'e', 'f']
third_list = ['g','h','q']
combined_list = []
for i in first_list:
for j in second_list:
for k in third_list:
combined_list.append(i + j + k)
print(combined_list)

Python merging sublist

I've got the following list :
[['a','b','c'],['d','e'],['f','g','h','i',j]]
I would like a list like this :
['abc','de','fghij']
How is it possible?
[Edit] : in fact, my list could have strings and numbers,
l = [[1,2,3],[4,5,6], [7], [8,'a']]
and would be :
l = [123,456, 7, 8a]
thx to all,
you can apply ''.join method for all sublists.
This can be done either using map function or using list comprehensions
map function runs function passed as first argument to all elements of iterable object
initial = ['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i', 'j']]
result = map(''.join, initial)
also one can use list comprehension
initial = ['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i', 'j']]
result = [''.join(sublist) for sublist in initial]
Try
>>> L = [['a','b','c'],['d','e'],['f','g','h','i','j']]
>>> [''.join(x) for x in L]
['abc', 'de', 'fghij']

Categories

Resources