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)
Related
I will start the description of the problem with an example so that the question is clear.
List of numbers: [1,2,3,4]
How can I get each successive string: [[1],[1,2],[1,2,3],[1,2,3,4],[2],[2,3],[2,3,4],[3],[3,4],[4]]
I've been trying to solve this problem for a while and managed to get [[1, 2, 3, 4], [2, 3, 4], [3, 4], [4]] with lots of useless repetitions.
list = [1,2,3,4]
i = 0
j = 0
tempList = []
sequancesList = []
while i < len(list):
while j < len(list):
tempList.append(list[j])
sequancesList.append(tempList)
j += 1
i += 1
j = i
tempList = []
def deleteDuplicates(list):
noduplist = []
for element in list:
if element not in noduplist:
noduplist.append(element)
return noduplist
finalSequancesList = deleteDuplicates(sequancesList)
print(finalSequancesList)
Here's how to do it:
list = [1,2,3,4]
sequancesList = []
for i in range(len(list)):
tmp = []
for j in range(i,len(list)):
tmp.append(list[j])
sequancesList.append(tmp[:])
print(sequancesList)
-> [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]]
Here is a generator that does exactly that:
def iter_successive(input_list):
for i in range(len(input_list)):
for j in range(i+1,len(input_list)+1):
yield input_list[i:j]
>>> list(iter_successive(input_list))
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]]
Comparable one-liner solution:
def iter_successive(input_list):
return (input_list[i:j] for i in range(len(input_list))
for j in range(i+1,len(input_list)+1))
Edit: As was stated in the comments, the approach below works only if the list contains whole, ascending numbers and not in other instances.
There are two ways to do this, either as a nested for-loop or a one-liner using list-comprehension. Both versions below:
Nested for-loop
nrs = list(range(1,5))
result = []
for i in nrs:
for j in range(i, max(nrs)+1):
result.append(list(range(i,j+1)))
print(result)
List-comprehension
result = [list(range(i,j+1)) for i in nrs for j in range(i, max(nrs)+1)]
print(result)
I have a nested list say:
lst = [[1,2,3,4], [2,3,4,5], [3,4,5,6]]
And I would like the output to be:
new_list = [[[1], [2], [3], [4]], [[2], [3], [4], [5]], [[3], [4], [5], [6]]]
this is what i am thinking, but I it is outputting a flat, list of list.
new_lst = []
for i in lst:
i = list(i)
for el in i:
new_list.append([el])
print(new_lst)
I would like to maintain the length of each predefined list in lst
Try List comprehension
[[ [e] for e in l] for l in lst]
You could use list comprehension and append every element to another list.
lst = [[1,2,3,4], [2,3,4,5], [3,4,5,6]]
new = [[[numbers] for numbers in elements] for elements in lst]
The above example adjusts for your desired output.
[[[1], [2], [3], [4]], [[2], [3], [4], [5]], [[3], [4], [5], [6]]]
You can use numpy's reshape np.reshape
>>> import numpy as np
>>> lst = np.array([[1,2,3,4], [2,3,4,5], [3,4,5,6]])
>>> lst
array([[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6]])
>>> lst.shape
(3, 4)
>>> lst.reshape(3,4,1)
array([[[1],
[2],
[3],
[4]],
[[2],
[3],
[4],
[5]],
[[3],
[4],
[5],
[6]]])
>>> lst.reshape(3,4,1).tolist()
[[[1], [2], [3], [4]], [[2], [3], [4], [5]], [[3], [4], [5], [6]]]
Another version, using recursion (you can have more level of depths in your input):
lst = [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]
def split(i):
if isinstance(i, list):
return [split(v) for v in i]
else:
return [i]
print(split(lst))
Prints:
[[[1], [2], [3], [4]], [[2], [3], [4], [5]], [[3], [4], [5], [6]]]
You could use helper function to have more flexibility later of how you divide the smaller lists. based on an answer from here.
def split_list(alist, wanted_parts=1):
length = len(alist)
return [ alist[i*length // wanted_parts: (i+1)*length // wanted_parts]
for i in range(wanted_parts) ]
lst = [[1,2,3,4], [2,3,4,5], [3,4,5,6]]
ret =[]
for mini_list in lst:
ret.append(split_list(mini_list, len(mini_list)))
I think you had the right idea using multiple for loops. This should work:
list = [[1,2,3,4], [2,3,4,5], [3,4,5,6]]
for i in range(0, 3):
for j in range(0, 4):
(list[i])[j] = [(list[i])[j]]
I'm trying to make a function that returns a list of n elements like the following:
factorial_list(4) → [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]
my output is [[1], [1], [2], [1], [2], [3], [1], [2], [3], [4]]
As you see I'm struggling to make the order of the inner lists. Any insights to what I should change in my code?
def factorial_list(n):
list2=[]
for i in range(1,n+1):
for j in range(1,i+1):
list2.append([j])
print(list2)
factorial_list(4)
Method 1: based on the logic of your code
def factorial_list(n):
final_list = []
for i in range(1, n+1):
temp = []
for j in range(1, i+1):
temp.append(j)
final_list.append(temp)
print(final_list)
factorial_list(4) # [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]
Method 2: a mix of for loop and list comprehensions
def factorial_list(n):
final_list = []
for i in range(1, n+1):
temp = [j for j in range(1, i+1)]
final_list.append(temp)
print(final_list)
factorial_list(4) # [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]
Method 3: using list comprehensions
def factorial_list(n):
final_list = [[j for j in range(1, i+1)] for i in range(1, n+1)]
print(final_list)
factorial_list(4) # [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]
You need to create a new list for each iteration of the first loop:
def factorial_list(n):
list2=[]
for i in range(1,n+1):
list3 = [] # <--- Create a new list for each iteration
for j in range(1,i+1):
list3.append(j)
list2.append(list3)
print(list2)
factorial_list(4)
# Output: [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]
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)
I am trying to make all the possible combinations of a list.
like:
l= [1,4,6,8,11,13]
combL = [ [1],[4],[6],[8],[11],[13],[1,4], .. ]
I tried to use
itertools.combinations(l, len(l))
but it didn't work out. Any function on Python that do that ?
from itertools import combinations
def get_all_combinations(input_list):
for i in xrange(len(input_list)):
for item in combinations(input_list, r = i + 1):
yield list(item)
input_list = [1,4,6,8,11,13]
for item in get_all_combinations(input_list):
print item
We have created a generator, so it is efficient as we don't have to store the entire combinations in memory. It is important for a combinations generator, because, often the number of combinations is very big.
But if you want to get all the combinations as list, then you can do
list(get_all_combinations(input_list))
# [[1], [4], [6], [8], [11], [13], [1, 4], [1, 6], [1, 8], [1, 11], [1, 13],..]
as a list:
[i for j in xrange(len(l)) for i in itertools.combinations(l, j+1)]
or as a generator:
(i for j in xrange(len(l)) for i in itertools.combinations(l, j+1))
res = []
for L in range(0, len(l)+1):
for subset in itertools.combinations(l, L):
res.append(list(subset))
Output:
[[], [1], [4], [6], [8], [11], [13], [1, 4], [1, 6], [1, 8], [1, 11], [1, 13], [4, 6], [4, 8], [4, 11],....