I get a nested list as input.
Simplified version is as under.
myList=[[[1,2,3],[4,5,6]],[[2,3,4],[3,4,5]],[[4,6,7],[5,7,9]]]
I wish to unpack it into a simple list of lists.
I can do like this--
simpleList=[]
for i in myList:
for j in i:
simpleList.append(j)
As desired, the simpleList is
[[1, 2, 3], [4, 5, 6], [2, 3, 4], [3, 4, 5], [4, 6, 7], [5, 7, 9]]
My question:-
What I did was, maybe, a beginner's coding approach.
Is there a more professional, efficient (and pythonic) approach to unpack this nested list?
Thanks.
EDIT:-
My method doesn't work for deeply nested lists.
e.g. [[[1,2,3],[4,5,6]],[[2,3,4],[3,4,5]],[[4,6,7],[5,7,9]],[[1,2,3],[4,5,6]],[[2,3,4],[3,4,5]],[[4,6,7],[5,7,9],[[1,2,3],[4,5,6]],[[2,3,4],[3,4,5]],[[4,6,7],[5,7,9]]]]
pl. refer to the comments to answers.
Use chain from itertools
from itertools import chain
myList=[[[1,2,3],[4,5,6]],[[2,3,4],[3,4,5]],[[4,6,7],[5,7,9]]]
print(list(chain.from_iterable(myList))) #print(list(chain(*myList)))
Output:
[[1, 2, 3], [4, 5, 6], [2, 3, 4], [3, 4, 5], [4, 6, 7], [5, 7, 9]]
You can do this using a recursive function in order to solve nested list with any depth.
def unwrap_list(mylist, result):
if any(isinstance(i, list) for i in mylist):
for value in mylist:
unwrap_list(value, result)
else:
result.append(mylist)
mylist = [[[1,2,3],[4,5,6]],[[2,3,4],[3,4,5]],[[4,6,7],[5,7,9]]]
result = []
unwrap_list(mylist, result)
print(result)
Another approach is using a generator.
def flatten(L):
for item in L:
if any(isinstance(i, list) for i in item):
yield from flatten(item)
else:
yield item
myList=[[[1,2,3],[4,5,6]],[[2,3,4],[3,4,5]],[[4,6,7],[5,7,9]]]
reduce(lambda x, y: x+y, myList)
Output:
[[1, 2, 3], [4, 5, 6], [2, 3, 4], [3, 4, 5], [4, 6, 7], [5, 7, 9]]
Related
For example:
t=[[1, 2, 3, 4, 5, 6], [2, 3, 4, 5, 6], [2, 3, 4, 5, 6], [3, 5], [4, 5, 6],[4,5,6],[6,7], [6], [1]]
I want to delete the short lists if the items are included in a long one, even the items are not continuous. So, I expect the result to be:
[[1, 2, 3, 4, 5, 6],[6,7]]
I might figure out this by myself, but my way is not smart enough. Could anyone help me here?
Since all the elements in a list is unique, AND I like using sets
here's my code. Haven't checked it's efficiency but it looks cleaner :D
t = [[1, 2, 3, 4, 5, 6], [2, 3, 4, 5, 6], [2, 3, 4, 5, 6], [3, 5], [4, 5, 6],[4,5,6],[6,7], [6], [1]]
t = [set(l) for l in t]
t = [list(x) for x in t if not any([x.issubset(y) for y in t if x != y])]
Sort from small to large, make them sets then pop them off the list to reduce the list size for every computation.
t=[[1, 2, 3, 4, 5, 6], [2, 3, 4, 5, 6], [2, 3, 4, 5, 6], [3, 5], [4, 5, 6],[4,5,6],[6,7], [6], [1]]
t = sorted(t, key=lambda x: len(x))
t = [set(x) for x in t]
for i in range(len(t)):
a = t.pop(0)
if not any([a.issubset(x) for x in t]):
print(a)
My approach is very simple
I check the last element is already present in our longer list. If we present then we don't need to add to the longer list if it is not the case then we will add to the longerlists
sorted_lists=[[1, 2, 3, 4, 5, 6], [2, 3, 4, 5, 6], [2, 3, 4, 5, 6], [3, 5], [4, 5, 6],[4,5,6],[6,7], [6], [1]]
sorted_big_lists =[]
for sorted_list in sorted_lists:
for test_list in sorted_big_lists:
if sorted_list[-1] in test_list:
break
else:
sorted_big_lists.append(sorted_list)
print(sorted_big_lists)
I have a list of lists, looks like this :
List=[[1,3],[3,4,7,9],[4,7],[2,4,5,3],[5,7,4]]
I want to classify the list elements according to their length, so the result looks like this:
2ElelmentSublist=[[1,3],[4,7]]
4ElementSublist=[[3,4,7,9],[2,4,5,3]]
....
And so on.
I read a post about itertools.groupby(),
But I couldn’t figure out how to apply it in my case.
Any pythonic way to do so?
Note: no need to have the result in separate variables,I need a way to know how many types of lengths I have, and a way to reach every group separately.
Thank you in advance.
You can't make lists with dynamic names to be decided at run-time (like your 2ElementSublist or so.)
But you can design a dictionary with keys as length, and values as lists of lists.
Try this:
result = {}
for L in List:
result.setdefault(len(L), list()).append(L)
print(result)
and you will see
{2: [[1, 3], [4, 7]], 4: [[3, 4, 7, 9], [2, 4, 5, 3]], 3: [[5, 7, 4]]}
.setdefault(k, d) either gives you access to the dictionary value of key k, or initialize with a default value d. And you append each list.
Might not be the most pythonic, but you can call values similar to how you wanted.
x = [[1,3],[3,4,7,9],[4,7],[2,4,5,3],[5,7,4]]
dic = {f"{len(i)}_elelment": [] for i in x}
for i in x:
dic[f"{len(i)}_elelment"].append(i)
# {'2_elelment': [[1, 3], [4, 7]],
# '4_elelment': [[3, 4, 7, 9], [2, 4, 5, 3]],
# '3_elelment': [[5, 7, 4]]}
Since you have mentioned you need the list grouped by len and need them in seperate variable I think you will be needing a dict as your final output.
from itertools import groupby, chain
from collections import defaultdict
List=[[1,3],[3,4,7,9],[4,7],[2,4,5,3],[5,7,4]]
res = defaultdict(list)
for _, v in groupby(sorted(List, key=len)):
l = list(chain(*v))
res[len(l)].append(l)
# Output : defaultdict(list,
{2: [[1, 3], [4, 7]],
3: [[5, 7, 4]],
4: [[3, 4, 7, 9], [2, 4, 5, 3]]})
You can try this:
List = [[1,3],[3,4,7,9],[4,7],[2,4,5,3],[5,7,4]]
sizes = set([(len(element)) for element in List])
result = {}
for element in List:
if len(element) not in result.keys():
result[len(element)] = []
result[len(element)].append(element)
print(result)
And result is:
{2: [[1, 3], [4, 7]], 4: [[3, 4, 7, 9], [2, 4, 5, 3]], 3: [[5, 7, 4]]}
Use groupby by len:
Ex:
from itertools import groupby
lst = [[1,3],[3,4,7,9],[4,7],[2,4,5,3],[5,7,4]]
print( [list(v) for k, v in groupby(sorted(lst, key=len), key=len)] )
#or
print( {k: list(v) for k, v in groupby(sorted(lst, key=len), key=len)} )
Output:
[[[1, 3], [4, 7]], [[5, 7, 4]], [[3, 4, 7, 9], [2, 4, 5, 3]]]
{2: [[1, 3], [4, 7]], 3: [[5, 7, 4]], 4: [[3, 4, 7, 9], [2, 4, 5, 3]]}
Let's say that:
atable = [[6, 2, 3, 1], [3, 4, 2, 1], [4, 8, 7, 6], [8, 9, 3, 7]]
without using numpy or flattened, how would you find the minimum value of the entire list?
I assume you can use a list but I am not sure.
Here are several approaches:
from itertools import chain
atable = [[6, 2, 3, 1], [3, 4, 2, 1], [4, 8, 7, 6], [8, 9, 3, 7]]
# Flatten the sublists into a single list
result = min(chain.from_iterable(atable))
# Find the min of each list, the find the min of mins
result = min(map(min, atable))
# Use a generator expression with nested loops
result = min(i for lst in atable for i in lst)
Here is a brute force approach:
atable = [[6, 2, 3, 1], [3, 4, 2, 1], [4, 8, 7, 6], [8, 9, 3, 7]]
min_list = []
for l in atable:
min_list.append(min(l))
min_val = min(min_list)
For your specific problem...
min(min(a_table))
As noted by #Prune this does not work. In fact min(a_table) returns the sublist with the smallest first element.
I apologize for a simple question, but I cannot find an answer to it in the archives.
what should i do to sort smaller lists within a larger list.
for example
lst=[[1, 2, 3, 4], [5,9,8,7], [9, 0, 1, 2, 3 ]]
should return
[1, 2, 3, 4]
[5,7,8,9]
[ 0, 1, 2, 3,9 ]
I tried to use lambda
lst.sort(key=lambda x: x.min())
and sorted
lst.sort(key=lambda x: sorted(x))
but neither works. could you please direct me a little bit. Thanks for your guidance.
Keep it simple, just use a list comprehension and sort the list inside the list:
Output:
[[1, 2, 3, 4], [5, 7, 8, 9], [0, 1, 2, 3, 9]]
So, with respect to your code, you can just do this:
lst = [sorted(x) for x in lst]
You can use a list comprehension to sort each sublist, then assign back to your main list
>>> lst = [sorted(i) for i in lst]
>>> lst
[[1, 2, 3, 4], [5, 7, 8, 9], [0, 1, 2, 3, 9]]
You could try something like this:
lst=[[1, 2, 3, 4], [5,9,8,7], [9, 0, 1, 2, 3 ]]
for x in lst:
x.sort()
I looped through lst and sorted each inner list.
You can do this:
>>> list(map(sorted, lst))
[[1, 2, 3, 4], [5, 7, 8, 9], [0, 1, 2, 3, 9]]
If you want to sort in place, you can do something like this:
any(ll.sort() for ll in lst)
(any is really only there to ditch the return values, which are all None; it will return false.)
You can write a function:
def sort_lst(lst):
lists = []
for l in lists:
l = l[:]
l.sort()
lists.append(l)
return lists
or
l = [[1, 2, 3, 6], [1, 2, 5, 6]]
l.sort(key=lambda x: x.sort())
print(l)
Output: [[1, 2, 3, 6], [1, 2, 5, 6]]
I have a list of list that I want to append a constant value to each sublist of the full list, for instance:
_lst = [[1, 2], [3, 4], [5, 6]]
and I want to append 7 to each of the sublist so that _lst becomes:
[[1, 2, 7], [3, 4, 7], [5, 6, 7]]
Is there a good way to complete the job (such as using zip)? Thanks!
for l in _lst:
l.append(7)
_lst = [ele + [7] for ele in _lst]
>>> tmp = [ i.append(7) for i in _lst ]
>>> print _lst
[[1, 2, 7], [3, 4, 7], [5, 6, 7]]