Related
I have a list J with len(J)=2. I want to create a sublist of each element in J[i] where i=0,1. I present the current and expected output.
J = [[1, 2, 4, 6, 7],[1,4]]
arJ1=[]
for i in range(0,len(J)):
J1=[J[i]]
arJ1.append(J1)
J1=list(arJ1)
print("J1 =",J1)
The current output is
J1 = [[[1, 2, 4, 6, 7], [1, 4]]]
The expected output is
J1 = [[[1], [2], [4], [6], [7]], [[1], [4]]]
you can try this,
J = [[1, 2, 4, 6, 7],[1,4]]
new_l = []
for l in J:
tmp = []
for k in l:
tmp.append([k])
new_l.append(tmp)
print(new_l)
this will give you
[[[1], [2], [4], [6], [7]], [[1], [4]]]
With simple list comprehension:
res = [[[i] for i in sub_l] for sub_l in J]
print(res)
[[[1], [2], [4], [6], [7]], [[1], [4]]]
You can do in one line with list comprehension:
[[[k] for k in l] for l in J]
J = [[1, 2, 4, 6, 7],[1,4]]
arJ1 = []
for in_list in J:
new_list = []
for x in in_list:
new_list.append([x])
arJ1.append(new_list)
print(arJ1)
I have a nested list in the form of [[1,2,3], [3,4,5], [8,6,2,5,6], [7,2,9]]
I would like to extract every first item into a new list, every second item into a new list and the rest into a new nested list:
a = [1,3,8,7] b = [2,4,6,2], c = [[3], [5], [2,5,6],[9]]
Is it possible to avoid using the for loop because the real nested list is quite large? Any help would be appreciated.
Ultimately, whatever your solution would be, you're gonna have to have a for loop inside your code and my advice would be to make it as clean and as readable as possible.
That being said, here's what I would propose:
arr = [[1,2,3], [3,4,5], [8,6,2,5,6], [7,2,9]]
first_arr, second_arr, third_arr = [], [], []
for nested in arr:
first_arr.append(nested[0])
second_arr.append(nested[1])
third_arr.append(nested[2:])
This is a naive, simple looped solution using list comprehensions, but see if it is fast enough for you.
l = [[1,2,3], [3,4,5], [8,6,2,5,6], [7,2,9]]
a = [i[0] for i in l]
b = [i[1] for i in l]
c = [i[2:] for i in l]
which returns:
>>a
[1, 3, 8, 7]
>>b
[2, 4, 6, 2]
>>c
[[3], [5], [2, 5, 6], [9]]
At the moment I cannot think a solution without for loops, I hope I will be able to update my answer later.
Here's a solution using for loops:
data = [[1,2,3], [3,4,5], [8,6,2,5,6], [7,2,9]]
list1 = []
list2 = []
list3 = []
for item in data:
else_list = []
for index, value in enumerate(item):
if index == 0:
list1.append(value)
elif index == 1:
list2.append(value)
else:
else_list.append(value)
list3.append(else_list)
print(list1)
print(list2)
print(list3)
Output
[1, 3, 8, 7]
[2, 4, 6, 2]
[[3], [5], [2, 5, 6], [9]]
Just for fun I share also a performance comparison, great job in using just one for loop Meysam!
import timeit
# a = [1,3,8,7] b = [2,4,6,2], c = [[3], [5], [2,5,6],[9]]
def solution_1():
data = [[1, 2, 3], [3, 4, 5], [8, 6, 2, 5, 6], [7, 2, 9]]
list1 = []
list2 = []
list3 = []
for item in data:
else_list = []
for index, value in enumerate(item):
if index == 0:
list1.append(value)
elif index == 1:
list2.append(value)
else:
else_list.append(value)
list3.append(else_list)
def solution_2():
arr = [[1, 2, 3], [3, 4, 5], [8, 6, 2, 5, 6], [7, 2, 9]]
first_arr, second_arr, third_arr = [], [], []
for nested in arr:
first_arr.append(nested[0])
second_arr.append(nested[1])
third_arr.append(nested[2:])
def solution_3():
l = [[1, 2, 3], [3, 4, 5], [8, 6, 2, 5, 6], [7, 2, 9]]
a = [i[0] for i in l]
b = [i[1] for i in l]
c = [i[2:] for i in l]
if __name__ == "__main__":
print("solution_1 performance:")
print(timeit.timeit("solution_1()", "from __main__ import solution_1", number=10))
print("solution_2 performance:")
print(timeit.timeit("solution_2()", "from __main__ import solution_2", number=10))
print("solution_3 performance:")
print(timeit.timeit("solution_3()", "from __main__ import solution_3", number=10))
Output
solution_1 performance:
9.580000000000005e-05
solution_2 performance:
1.7200000000001936e-05
solution_3 performance:
1.7499999999996685e-05
Suppose the nested list has unknown depth, then we'd have to use recursion
def get_elements(l):
ret = []
for elem in l:
if type(elem) == list:
ret.extend(get_elements(elem))
else:
ret.append(elem)
return ret
l = [1,2,[3,4],[[5],[6]]]
print(get_elements(l))
# Output: [1, 2, 3, 4, 5, 6]
Though it is not quite recommended to use unknown-depth nested lists in the first place.
I am trying to append a list of lists with Python but there is an error. My problem is just with append function. I explain my problem better. I am using a loop. The first time the append function works fine. But for the second time, the function does not work.
When we do the first loop, we get the right result:
list1 = [1,2,3]
list2 = [4,5,6]
list3 = []
list3.append(list1)
list3.append(list2)
print(list3)
result:
[[1, 2, 3], [4, 5, 6]]
With the second loop, append does not work correctly. One extra bracket.
liste4 = []
liste4.append(list3)
liste4.append(list1)
print(liste4)
result:
[[[1, 2, 3], [4, 5, 6]], [1, 2, 3]]
But the result I want is this:
[[1, 2, 3], [4, 5, 6], [1, 2, 3]]
Define list3 as an empty list and append to it :
list1 = [1,2,3]
list2 = [4,5,6]
list3 = []
list3.append(list1)
list3.append(list2)
print(list3)
Output :
[[1, 2, 3], [4, 5, 6]]
you could just do list3 = [list1, list2]
If you want it in a function, here is a go a a List of List creator, which may take multiple lists as the input:
def LoL(*lists):
out = [x for x in lists]
return out
list1 = [1,2,3]
list2 = [4,5,6]
list3 = [7,8,9]
list4 = LoL(list1,list2,list3)
list4
>>> [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
list1 = [1,2,3]
list2 = [4,5,6]
list3 = []
list3.append(list1)
list3.append(list2)
print(list3)
result:
[[1, 2, 3], [4, 5, 6]]
With the second loop:
liste4 = list3
liste4.append(list1)
print(liste4)
result:
[[1, 2, 3], [4, 5, 6], [1, 2, 3]]
I have this nested list:
list_1 = [[1,2,3], [1,2,3,4,5,6], [1,2,3,4,5,6,7,8,9]]
Count of sublist elements are always in mulitple of 3. I want to have 3 elments in each sublist. Desired output:
list_1 = [[1,2,3], [1,2,3], [4,5,6],[1,2,3], [4,5,6], [7,8,9]]
I can achieve this but first i have to flatten the list and then create the nested list. My code:
list_1 = [values for sub_list in lists_1 for values in sub_list] # flatten it first
list_1 = [list_1[i:i+3] for i in range(0, len(list_1), 3)]
Is there a way to skip the flatten step and get the desired result?
You can use a nested list comprehension:
list_1 = [[1,2,3], [1,2,3,4,5,6], [1,2,3,4,5,6,7,8,9]]
result = [i[j:j+3] for i in list_1 for j in range(0, len(i), 3)]
Output:
[[1, 2, 3], [1, 2, 3], [4, 5, 6], [1, 2, 3], [4, 5, 6], [7, 8, 9]]
Here is how you can use nested list comprehensions:
list_1 = [[1,2,3],[1,2,3,4,5,6],[1,2,3,4,5,6,7,8,9]]
list_1 = [a for b in list_1 for a in b]
list_1 = [list_1[i:i+3] for i in range(0,len(list_1),3)]
print(list_1)
Output:
[[1, 2, 3], [1, 2, 3], [4, 5, 6], [1, 2, 3], [4, 5, 6], [7, 8, 9]]
To put my two cents in, you could use two generator functions, one that flattens the list (with an arbitrarly nested list) and one that yields pairs of n values:
def recursive_yield(my_list):
for item in my_list:
if isinstance(item, list):
yield from recursive_yield(item)
else:
yield item
def taken(gen, number = 3):
buffer = []
for item in gen:
if len(buffer) < number:
buffer.append(item)
else:
yield buffer
buffer = []
buffer.append(item)
if buffer:
yield buffer
result = [x for x in taken(recursive_yield(list_1))]
Here are some examples of the in- / outputs:
list_1 = [[1,2,3], [1,2,3,4,5,6], [1,2,3,4,5,6,7,8,9]]
# -> [[1, 2, 3], [1, 2, 3], [4, 5, 6], [1, 2, 3], [4, 5, 6], [7, 8, 9]]
list_1 = [1,2,3,4,5,6]
# -> [[1, 2, 3], [4, 5, 6]]
list_1 = [1,2,[[1,2,4,5], [[[[1,10,9]]]]]]
# -> number = 5
# -> [[1, 2, 1, 2, 4], [5, 1, 10, 9]]
Thus, the solution is much more flexible than slicing alone.
I have a list:
lst = [[7], [4, 3, 5, 8], [1, 3]]
How can I multiply each element in list by it position like this:
[[7 * 0],[4 * 0 + 3 * 1 + 5 * 2 + 8 * 3], [1 * 0 + 3 * 1]]
And print answer:
answer = [[0], [37], [3]]
You can use a list comprehension with sum and enumerate:
L = [[7], [4, 3, 5, 8], [1, 3]]
res = [[sum(i*j for i, j in enumerate(sublist))] for sublist in L]
print(res)
[[0], [37], [3]]
Or if you are happy to use a 3rd party library, you can use NumPy:
import numpy as np
L = [[7], [4, 3, 5, 8], [1, 3]]
res = [np.arange(len(sublist)).dot(sublist) for sublist in L]
print(res)
[0, 37, 3]
This is a possible solution ...
a_list = [[7], [4, 3, 5, 8], [1, 3]]
new_list = []
for sub_list in a_list:
sublistsum = 0
for i, value in enumerate(sub_list):
sublistsum = sublistsum + i * value
new_list.append([sublistsum])
print(new_list)