How to reverse each item in the nested list? - python

Lists are used to store multiple items in a single variable.
Lists are created using square brackets.
I want to reverse each item in the list of a list.
I tried reversed and [::1] method but it did not gave me desired output.
Here is my list
list1 = [1, 2, 3, [4, 5, 6], 6, 7, [8, 9, 10]]
I tried print(list1[::-1]) and reversed(list1) and got this output
output: [[8, 9, 10], 7, 6, [4, 5, 6], 3, 2, 1]
How could I get this output?
output: [[10, 9, 8], 7, 6, [6, 5, 4], 3, 2, 1]

You can use a recursive function.
def revall(l):
return [revall(x) if isinstance(x, list) else x for x in l[::-1]]
print(revall([1, 2, 3, [4, 5, 6], 6, 7, [8, 9, 10]]))

Try this one:
list1 = [1, 2, 3, [4, 5, 6], 6, 7, [8, 9, 10]]
list1.reverse()
for sub_list in list1:
if type(sub_list) is list:
sub_list.reverse()
print(list1)

Related

How do I stop iterating based on the number of elements on my list?

I have a project wherein I have to get the follow-up elements of elements in on_time.
For example:
j_set = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
s_follow_int = [[2, 3], 4, [5, 6], [6, 8], [7, 8], 9, 8, 10, 10, 11]
on_time = [4, 5]
The code I have looks like this:
# element in on_time except 1, get follow_finish_act
follow_finish_act = []
for a, d in zip(j_set, s_follow_int):
if a in on_time and a != 1:
if len(on_time) > 1:
follow_finish_act.append(d)
else:
follow_finish_act = d
Output I am getting:
follow_finish_act = [[6, 8], [7, 8]]
Expected Output:
follow_finish_act = [6, 7, 8]
I am having trouble when length of on_time is more than 1. I think the problem is flattening the irregular lists (can be nested and integer) without duplicates. Since, I cannot get my expected output.
Any help/suggestions would be appreciated! Thank you!
Edit: Code I used for trying to flatten output of follow_finish_act
def flatten(lss):
for item in lss:
try:
yield from flatten(item)
except TypeError:
yield item
You could avoid duplicates by using set instead of list
j_set = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
s_follow_int = [[2, 3], 4, [5, 6], [6, 8], [7, 8], 9, 8, 10, 10, 11]
on_time = [4, 5]
follow_finish_act = set()
for a, d in zip(j_set, s_follow_int):
if a in on_time and a != 1:
if len(on_time) > 1:
follow_finish_act.update(d)
else:
follow_finish_act.update(d)
print(follow_finish_act)
# prints {6,7,8}
print(list(follow_finish_act))
# prints[8,7,6]
Its difficult to tell what you really want, but looking at the code a lot of it seems superfluous. Try this instead:
j_set = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
s_follow_int = [[2, 3], 4, [5, 6], 8, 7, 9, 8, 10, 10, 11]
on_time = [6, 5]
follow_finish_act = []
for a, d in zip(j_set, s_follow_int):
if a in on_time:
follow_finish_act.append(d)
print(follow_finish_act)
Output:
[7, 9]
If you then get output like: [9], you could do this afterwards:
if len(follow_finish_act) == 1:
follow_finish_act = follow_finish_act[0]

Loop through a list of lists to find max value

The following shows a sample of a list of lists that I have:
[[['point_5', [5, 6, 7, 8], 11.0],
['point_5', [6, 7, 8, 9],12.57]],
[['point_18', [3, 4, 5, 6],6.25],
['point_18', [3, 5, 6, 7],7.2],
['point_18', [4, 5, 6, 7],7.55],
['point_18', [6, 7, 8, 9],14.0],
['point_19', [3, 5, 6, 7],8.166],
['point_19', [5, 6, 7, 8],9.285],
['point_19', [6, 7, 8, 9],11.0]]]
I need to define a loop which searches through each element of this list of lists and returns the maximum value of the last element of each list. What I mean is that for example for [6,7,8,9] we have:
['point_5', [6, 7, 8, 9], 12.57]
['point_18', [6, 7, 8, 9],14.0]
['point_19', [6, 7, 8, 9],11.0]
Since max(12.57,14.0,11.0) = 14.0 then what I am looking for is a list that one of its element is [point_18,[6,7,8,9],14.0].
Another example is that since the only element that has [3, 4, 5, 6] is ['point_18', [3, 4, 5, 6],6.25] then another element of the new list should be [point_18,[3,4,5,6],6.25].
In fact, the new list of lists that I am trying to create should be like the following list:
New_list = [['point_5',[5,6,7,8],11.0],['point_18',[6,7,8,9],14.0],['point_18', [3, 4, 5, 6],6.25],['point_19', [3, 5, 6, 7],8.166],['point_18', [4, 5, 6, 7],7.55]].
I am not sure if it is a good idea or not but what I have done is that first I tried to extract each unique [x,y,i,j] in a list through the following code:
A = []
for i in bob:
for j in i:
A.append(j[1])
import itertools
A.sort()
B = list(A for A,_ in itertools.groupby(A))
Now B is:
[[3, 4, 5, 6],
[3, 5, 6, 7],
[4, 5, 6, 7],
[5, 6, 7, 8],
[6, 7, 8, 9]]
Then I want to search for each element of this list in the main lists of list and find the max value.
Any help would be appreciated.
I think you can try breaking the problems into parts.
I don't know if you had a list that already done the first step, so I am assuming no
This is the list that I am working with:
your_list = [['point_5', [5, 6, 7, 8], 11.0],
['point_5', [6, 7, 8, 9],12.57],
['point_18', [3, 4, 5, 6],6.25],
['point_18', [3, 5, 6, 7],7.2],
['point_18', [4, 5, 6, 7],7.55],
['point_18', [6, 7, 8, 9],14.0],
['point_19', [3, 5, 6, 7],8.166],
['point_19', [5, 6, 7, 8],9.285],
['point_19', [6, 7, 8, 9],11.0]]
First, try sorting the list in a dict.
sorted_dict = {}
for i in your_list:
if tuple(i[1]) in sorted_dict:
sorted_dict[tuple(i[1])].append(i)
else:
sorted_dict[tuple(i[1])] = [i]
Then, select the max and put it in a list.
return_list = []
for key, values in sorted_dict.items():
print(values)
return_list.append(sorted(values, key=lambda x: float(x[2]))[-1]) # sort the list according to the third value
Return list now should have the value you're looking for
I am not sure if this is what you're looking for so comment if there's any problem

padding while creating sublists

Is there an elegant way how to pad the last sublist with zeroes while creating sublists from a list of integers?
So far I have this oneliner and need to fill the last sublist with 2 zeroes
[lst[x:x+3] for x in range(0, len(lst), 3)]
for example
lst =[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result should be:
[1,2,3][4,5,6][7,8,9][10,0,0]
With itertools.zip_longest, consuming the same iterator created off of the list, and fill in the missing values as 0 :
[[*i] for i in itertools.zip_longest(*[iter(lst)] * 3, fillvalue=0)]
Example:
In [1219]: lst =[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [1220]: [[*i] for i in itertools.zip_longest(*[iter(lst)] * 3, fillvalue=0)]
Out[1220]: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 0, 0]]
Without itertools:
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print([lst[x:x+3]+[0]*(x-len(lst)+3) for x in range(0, len(lst), 3)])
Prints:
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 0, 0]]

Replacing items in a list in all possible permutations

Let's say I have a list or an array of the type:
mylist = [1, 2, 3, 4]
And I want to replace an item in this list. Normally I would use something like the following:
mylist[2] = 7
That works well. However, can someone explain how to create all possible permutations of mylist when replacing one or more items in mylist. For example, I want to create the following:
[7, 2, 3, 4]
[7, 7, 3, 4]
[7, 2, 7, 4]
[7, 7, 7, 4]
[7, 2, 3, 7]
...(and so on)
I know I can use itertools to generate all possible permutations, but how can I specify that I want to substitute an item in all possible locations in the list before generating the permutations? Here is how I tried to use itertools:
list(itertools.permutations([1,2,3,4,7], 4))
This doesn't work because it doesn't substitute 7 more than one time per permutation, and it also generates permutations that do not include the number 7.
Use itertools.combinations to find the indices to replace:
replace = 7
mylist = [1, 2, 3, 4]
for i in range(1, len(mylist) + 1):
for selected in itertools.combinations(range(len(mylist)), i):
res = mylist[:]
for n in selected:
res[n] = replace
print(res)
Output:
[7, 2, 3, 4]
[1, 7, 3, 4]
[1, 2, 7, 4]
[1, 2, 3, 7]
[7, 7, 3, 4]
[7, 2, 7, 4]
[7, 2, 3, 7]
[1, 7, 7, 4]
[1, 7, 3, 7]
[1, 2, 7, 7]
[7, 7, 7, 4]
[7, 7, 3, 7]
[7, 2, 7, 7]
[1, 7, 7, 7]
[7, 7, 7, 7]
You can create a function and just pass the list and value to that function and you get what you want :
import itertools
def replaced_it(list_1,value):
final_list = []
len_=len(list_1)
track_index = [k for k, j in enumerate(list_1)]
for i in range(len(track_index) + 1):
empty_list = [value]
replaced_one = list_1[:]
for ia in itertools.permutations(track_index, r=i):
if ia:
for i, j in zip(ia, empty_list * len(ia)):
replaced_one[i] = j
if replaced_one not in final_list:
final_list.append(replaced_one)
replaced_one = list_1[:]
return final_list
print(replaced_it([1,2,3,4],7))
output:
[[7, 2, 3, 4], [1, 7, 3, 4], [1, 2, 7, 4], [1, 2, 3, 7], [7, 7, 3, 4], [7, 2, 7, 4], [7, 2, 3, 7], [1, 7, 7, 4], [1, 7, 3, 7], [1, 2, 7, 7], [7, 7, 7, 4], [7, 7, 3, 7], [7, 2, 7, 7], [1, 7, 7, 7], [7, 7, 7, 7]]

Better way to get sublist in python

I am working on the following problem:
This function returns a list of all possible sublists in L of length n without skipping elements in L. The sublists in the returned list should be ordered in the way they appear in L, with those sublists starting from a smaller index being at the front of the list.
Example 1, if L = [10, 4, 6, 8, 3, 4, 5, 7, 7, 2] and n = 4 then your function should return the list [[10, 4, 6, 8], [4, 6, 8, 3], [6, 8, 3, 4], [8, 3, 4, 5], [3, 4, 5, 7], [4, 5, 7, 7], [5, 7, 7, 2]]
My solution works but how can I make it shorter? What is a better way to do this?
def getSublists(L, n):
newN = n
myList = []
for i in range(len(L)):
orginalLen = L[i:n]
if(len(orginalLen) == n):
myList.append(L[i:n])
n = n + 1
else:
myList.append(L[i:n])
n = n + 1
if(newN == 1):
print(myList)
else:
print(myList[:len(myList)-(n-1)])
getSublists([10, 4, 6, 8, 3, 4, 5, 7, 7, 2],4)
getSublists([1], 1)
getSublists([0, 0, 0, 0, 0], 2)
OUTPUT
[[10, 4, 6, 8], [4, 6, 8, 3], [6, 8, 3, 4], [8, 3, 4, 5], [3, 4, 5, 7], [4, 5, 7, 7], [5, 7, 7, 2]]
[[1]]
[[0, 0], [0, 0], [0, 0], [0, 0]]
l = [1,2,3,4,5,6,87,9]
n = ..
print [l[i:i+n] for i in range(len(l)-n+1)]
maybe you need.
In one line:
get_sublists = lambda ls, n: [ls[x:x+n] for x in range(len(ls)-n+1)]
get_sublists([10, 4, 6, 8, 3, 4, 5, 7, 7, 2], 4)
[[10, 4, 6, 8], [4, 6, 8, 3], [6, 8, 3, 4], [8, 3, 4, 5], [3, 4, 5, 7], [4, 5, 7, 7], [5, 7, 7, 2]]
def get_sublists(L, n):
return [ L[i:i+n] for i in range(len(L)-n) ]
I completed the program a little better understanding of the reader.
def getSublists(L, n):
new_list = []
for i in range(len(L)-n+1):
a = L[i:i+n]
new_list.append(a)
return new_list
answer:
[[10, 4, 6, 8],
[4, 6, 8, 3],
[6, 8, 3, 4],
[8, 3, 4, 5],
[3, 4, 5, 7],
[4, 5, 7, 7],
[5, 7, 7, 2]]
This is pretty readable I think, to understand the concept. The idea here is to iterate through the numbers from 0 to the length of L, minus 4. And just take the sublist of L from your current index i, to i+4. Iterating to length-4 ensures you don't try to access an index out of bounds!
>>> for i in range(len(L)-4+1):
print L[i:i+4]
[10, 4, 6, 8]
[4, 6, 8, 3]
[6, 8, 3, 4]
[8, 3, 4, 5]
[3, 4, 5, 7]
[4, 5, 7, 7]
[5, 7, 7, 2]

Categories

Resources