Related
have a list like this
> lst1=[1,2,3]
> lst2=[[],['abc','bcd','acd'],[],['sdf','ghj','klh'],[]]
want output like :
> [[1],['abc','bcd','acd'],[2],['sdf','ghj','klh'],[3]]
have tried to split the list of 2nd list and then aggregating by
One approach:
lst1=[1,2,3]
lst2=[[],['abc','bcd','acd'],[],['sdf','ghj','klh'],[]]
it = iter(lst1)
for i in lst2[::2]:
i.append(next(it))
print(lst2)
Output
[[1], ['abc', 'bcd', 'acd'], [2], ['sdf', 'ghj', 'klh'], [3]]
An alternative that returns a new list:
it = iter(lst1)
res = [l if i % 2 == 1 else [*l, next(it)] for i, l in enumerate(lst2)]
print(res)
Output
[[1], ['abc', 'bcd', 'acd'], [2], ['sdf', 'ghj', 'klh'], [3]]
Here is an approach similar to that of Dani Mesajo. Make an iterator of the fill list, then pull the next item for empty lists.
l1 = iter([1, 2, 3])
l2 = [[], ["abc", "bcd", "acd"], [], ["sdf", "ghj", "klh"], []]
print([l or next(l1) for l in l2])
yields:
➜ python listfill.py
[1, ['abc', 'bcd', 'acd'], 2, ['sdf', 'ghj', 'klh'], 3]
This is my solution that checks if an element from lst2 is an empty list, and if it is, the corresponding item from lst1 is added to new_list, otherwise the corresponding item from lst2 is added. n is used as the index to use for lst1, which is incremented each time an item from lst1 is added instead of an item from lst2.
lst1=[1,2,3]
lst2=[[],['abc','bcd','acd'],[],['sdf','ghj','klh'],[]]
new_list = []
n = 0
for l in lst2:
if len(l) == 0:
new_list.append([lst1[n]])
n += 1
else:
new_list.append(l)
print(new_list)
A simple loop will do the job:
Code:
import copy
lst1 = [1,2,3]
lst2 = [[],['abc','bcd','acd'],[],['sdf','ghj','klh'],[]]
merged_lst = copy.deepcopy(lst2)
for i in range(len(lst1)):
merged_lst[i*2].append(lst1[i])
print(merged_lst)
Output:
[[1], ['abc', 'bcd', 'acd'], [2], ['sdf', 'ghj', 'klh'], [3]]
We've to check whether the inner list of lst2 is empty or not, if yes, add the element of lst1 to it. We'll do it using two loop. One loop for iterating lst1 and second to ieratw lst2. The moment we get empty list, we'll add element of lst1 to it. Your code:
lst1=[1,2,3]
lst2=lst2 = [[],['abc','bcd','acd'],[],['sdf','ghj','klh'],[]]
for i in lst1:
for j in lst2:
if len(j)==0:
j.append(i)
break #break the inner for loop
print(lst2)
I have a nested list:
regions = [[1,2,3],[3,4],[1,3,4],[1,2,3,5]]
I want to remove every list in this nested list which is contained in another one, i.e., [3,4] contained in [1,3,4] and [1,2,3] contained in [1,2,3,5], so the result is:
result = [[1,3,4],[1,2,3,5]]
So far I'm doing:
regions_remove = []
for i,reg_i in enumerate(regions):
for j,reg_j in enumerate(regions):
if j != i and list(set(reg_i)-set(reg_j)) == []:
regions_remove.append(reg_i)
regions = [list(item) for item in set(tuple(row) for row in regions) -
set(tuple(row) for row in regions_remove)]
And I've got: regions = [[1, 2, 3, 5], [1, 3, 4]] and this is a solution, but I'd like to know what's the most pythonic solution?
(sorry for not posting my entire code before, I'm a new to this...
Here is a solution with list comprehension and all() function :
nested_list = [[1,2,3],[3,4],[1,3,4],[1,2,3,5],[2,5]]
result = list(nested_list) #makes a copy of the initial list
for l1 in nested_list: #list in nested_list
rest = list(result) #makes a copy of the current result list
rest.remove(l1) #the list l1 will be compared to every other list (so except itself)
for l2 in rest: #list to compare
if all([elt in l2 for elt in l1]): result.remove(l1)
#if all the elements of l1 are in l2 (then all() gives True), it is removed
returns:
[[1, 3, 4], [1, 2, 3, 5]]
Further help
all() built-in function: https://docs.python.org/2/library/functions.html#all
copy a list: https://docs.python.org/2/library/functions.html#func-list
list comprehension: https://www.pythonforbeginners.com/basics/list-comprehensions-in-python
I'm definitely overlooking a simpler route, but this approach works
list comprehension
from itertools import product
l = [[1,2,3],[3,4],[1,3,4],[1,2,3,5]]
bad = [i for i in l for j in l if i != j if tuple(i) in product(j, repeat = len(i))]
final = [i for i in l if i not in bad]
Expanded explanation
from itertools import product
l = [[1,2,3],[3,4],[1,3,4],[1,2,3,5]]
bad = []
for i in l:
for j in l:
if i != j:
if tuple(i) in product(j, repeat = len(i)):
bad.append(i)
final = [i for i in l if i not in bad]
print(final)
[[1, 3, 4], [1, 2, 3, 5]]
The following is the first line from my list l:
[0.0, 753.128, 990.43, 686.832, 366.922, -93.454, 1.0]
This is the result of:
print l[0]
I want to take all the first element from all such *lines of my list and assign them to another list. How can I do it in python?
Using a list comprehension:
lists = [[1,2,3], [4,5,6]]
[ l[0] for l in lists ]
That would do it. Nicer is to use map: you map a list of lists to a list of their heads:
map( lambda l: l[0], lists )
If performance is important, you may want to create an iterator over the heads of your lists:
heads = itertools.imap( lambda l: l[0], enumerate(lists))
for head in heads:
print head
Basic list comprehension:
another_list = [sublist[0] for sublist in l]
Try this:
a = [[1,2,3], ['a','b','c'], [True, False]]
first_elements = [e[0] for e in a]
print first_elements
>>> [1, 'a', True]
Something like this?
>>> a = [1, 2, 3, 4]
>>> b = [5,6,7,8]
>>> ab = [a, b]
>>> map (lambda x : x[0], ab)
[1, 5]
newlist=[]
for l in lst:
newlist.append(l[0])
given à list of lists:
L = [[1,2,3], [3,4,5], [1,2,3]]
how to get a list where each list is unique:
L = [[1,2,3], [3,4,5]]
thanks
If you don't care about the order of sub-lists:
In [11]: list(map(list, set(map(tuple, L))))
Out[11]: [[3, 4, 5], [1, 2, 3]]
Better yet, you should probably just move to using sets of tuples as your data structure.
Bit of jinking around but how about this?
[list(el) for el in set(tuple(el) for el in L)]
It works because lists can't be compared to one another but tuples can. The error message gives it away if you try to directly make a set from a list of lists:
unhashable type: 'list'
L = [[1,2,3], [3,4,5], [1,2,3]]
newlist = []
for item in L:
if item not in newlist:
newlist.append(item)
You can convert to a set of tuples and then back to a list.
L = [[1,2,3], [3,4,5], [1,2,3]]
setL = set(tuple(i) for i in L)
newL = list(list(i) for i in setL)
print newL
[[3, 4, 5], [1, 2, 3]]
Possible Duplicate:
How can I turn a list into an array in python?
How can I turn a list such as:
data_list = [0,1,2,3,4,5,6,7,8]
into a list of lists such as:
new_list = [ [0,1,2] , [3,4,5] , [6,7,8] ]
ie I want to group ordered elements in a list and keep them in an ordered list. How can I do this?
Thanks
This groups each 3 elements in the order they appear:
new_list = [data_list[i:i+3] for i in range(0, len(data_list), 3)]
Give us a better example if it is not what you want.
This assumes that data_list has a length that is a multiple of three
i=0
new_list=[]
while i<len(data_list):
new_list.append(data_list[i:i+3])
i+=3
Something like:
map (lambda x: data_list[3*x:(x+1)*3], range (3))
Based on the answer from Fred Foo, if you're already using numpy, you may use reshape to get a 2d array without copying the data:
import numpy
new_list = numpy.array(data_list).reshape(-1, 3)
new_list = [data_list[x:x+3] for x in range(0, len(data_list) - 2, 3)]
List comprehensions for the win :)
The following function expands the original context to include any desired list of lists structure:
def gen_list_of_lists(original_list, new_structure):
assert len(original_list) == sum(new_structure), \
"The number of elements in the original list and desired structure don't match"
list_of_lists = [[original_list[i + sum(new_structure[:j])] for i in range(new_structure[j])] \
for j in range(len(new_structure))]
return list_of_lists
Using the above:
data_list = [0,1,2,3,4,5,6,7,8]
new_list = gen_list_of_lists(original_list=data_list, new_structure=[3,3,3])
# The original desired outcome of [[0,1,2], [3,4,5], [6,7,8]]
new_list = gen_list_of_lists(original_list=data_list, new_structure=[2,3,3,1])
# [[0, 1], [2, 3, 4], [5, 6, 7], [8]]
The below one is more optimized and quite straightforward.
data_list = [0,1,2,3,4,5,6,7,8]
result =[]
i=0
while i <(len(data_list)-2):
result.append(data_list[i:i+3])
i+=3
print(result)
**output**
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
Here is a generalized solution
import math
data_list = [0,1,2,3,4,5,6,7,8]
batch_size=3
n_batches=math.ceil(len(data_list)/batch_size)
[data_list[x*batch_size:min(x*batch_size+batch_size,len(data_list))]
for x in range(n_batches)]
It works even if the last sublist is not the same size as the rest (<batch_size)
Do you have any sort of selection criteria from your original list?
Python does allow you to do this:
new_list = []
new_list.append(data_list[:3])
new_list.append(data_list[3:6])
new_list.append(data_list[6:])
print new_list
# Output: [ [0,1,2] , [3,4,5] , [6,7,8] ]