As far as I know this question hasn't been asked.
If I have two lists like so:
a_list = [[1,2], [5,6], [7,8]]
b_list = [3, 4]
How can I iterate over them while checking if the values of b_list fit the ascending order of the numbers in a_list? in this case b_list fits between [1, 2] and [5, 6] and should be appending in that spot. How would this be done in python?
When I use a for loop it tells me:
"TypeError: 'int' object is not subscriptable"
I used this code:
for sub_lst in a_lst:
for lst in sub_lst:
You can simply append b to a then sort all elements:
>>> a_list = [[1, 2], [5, 6], [7, 8]]
>>> b_list = [3, 4]
>>> sorted(a_list + [b_list])
[[1, 2], [3, 4], [5, 6], [7, 8]]
If you want to stick with what you have (with the for loop) do
for index, sub_list in enumerate(a_list):
if sub_list[0] < b_list[0]:
continue
elif sub_list[0] == b_list[0] and sub_list[1] < b_list[1]:
continue
else:
a_list.insert(index, b_list)
break
This will iterate through the list till you get to the right position (takes account of the second spot in case the first one is the same ie [3, 3] and b_list = [3,5]) and append b_list at the index where it stopped
you could use bisect_left to find the insertion index using a binary search (I'm assuming that there are no range overlaps in your data)
a_list = [[1,2], [5,6], [7,8]]
b_list = [3, 4]
from bisect import bisect_left
i = bisect_left(a_list,b_list)
a_list.insert(i,b_list)
print(a_list)
[[1, 2], [3, 4], [5, 6], [7, 8]]
You can also do it by sequentially searching for the index of the first item that is greater than b_list.
a_list = [[1,2], [5,6], [7,8]]
b_list = [3, 4]
i = next((i for i,a in enumerate(a_list) if b_list<a),len(a_list))
a_list.insert(i,b_list)
print(a_list)
[[1, 2], [3, 4], [5, 6], [7, 8]]
Related
This question already has answers here:
Is there a zip-like function that pads to longest length?
(8 answers)
Closed 1 year ago.
I got two lists as shown below:
a = [[[1,2], [3, 4], [5,6]], [[8,9],[10,11]]]
b = [[[1,2], [1,3],[2,3],[3, 4],[4,6],[5,6]],[[8,9],[9,10],[10,11]]]
The values in both lists are a group of list of coordinate points. And you can notice that some of the coordinate points in list a are also shown in list b
My goal is to slice list b from the given coordinate points from list a and then append in a new list. Here is an example of what I expect to get.
Example
The first item of list a is [[1,2], [3, 4], [5,6]] which I named as a[0] while that of list b is [[1,2], [1,3],[2,3],[3, 4],[4,6],[5,6]] which I named as b[0]. Therefore, a[0] is a set of b[0]
I want to slice b[0] based on the values in a[0] into a new list which looks like [[[1,2],[1,3],[2,3],[3,4]],[[3, 4],[4,6],[5,6]]]. In other words, a[0] serves as the slicing index of b[0].
Below is my code, and I do not have any idea to execute the above statement.
for items in a:
c.append([])
for i,j in zip(range(len(items)),range(len(b))):
if i < len(items)-1:
L_i = b[j][b[j].index(a[i]):b[j].index(a[i+1])+1]
L_i = list(tuple(item) for item in L_i)
elif i == len(concave_points)-1:
temp1 = b[j][b[j].index(a[i]):]
temp2 =b[j][0:b[j].index(a[0])+1]
L_i = temp1 + temp2
L_i = list(tuple(item) for item in L_i)
And an error ValueError: [[1, 2], [3, 4], [5, 6]] is not in list is occured.
Thanks a lot.
You can zip the lists instead of their length and just slice the sublists by index
a = [[[1, 2], [3, 4], [5, 6]], [[8, 9], [10, 11]]]
b = [[[1, 2], [1, 3], [2, 3], [3, 4], [4, 6], [5, 6]], [[8, 9], [9, 10], [10, 11]]]
c = []
for aa, bb in zip(a, b):
for i in range(len(aa) - 1):
c.append(bb[bb.index(aa[i]):bb.index(aa[i + 1]) + 1])
print(c) # [[[1, 2], [1, 3], [2, 3], [3, 4]], [[3, 4], [4, 6], [5, 6]], [[8, 9], [9, 10], [10, 11]]]
And as on liner with list comprehensions
c = [bb[bb.index(aa[i]):bb.index(aa[i + 1]) + 1] for aa, bb in zip(a, b) for i in range(len(aa) - 1)]
a = [[1, 2], [3, 4], [5, 6]]
b = [[1, 2], [1, 3], [2, 3], [3, 4], [4, 6], [5, 6]]
union_a_b = []
a.extend(b)
for pair in a:
if pair not in union_a_b:
union_a_b.append(pair)
else:
continue
print(union_a_b)
I have two lists and need to join them by rows. The output looks like list3 (below). Actually there aren't any commas between the bracketed pairs. I've tried a few different things and can't figure this out.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
my desired output is: list3 = [[1 4], [2 5], [3 6]]
Use zip
[[i, j] for i,j in zip(list1 , list1 )]
[[1, 4], [2, 5], [3, 6]]
I am not sure if you want the final list to be list of lists or not but I will assume you do,
list1 = [1, 2, 3]
list2 = [4, 5, 6]
res = [[*np.asarray([list1, list2])[:,i]] for i in range(3)]
res = [[1, 4], [2, 5], [3, 6]]
I have a nested list and I am trying to replace a certain element of the list with something else.
NL = [[1,2,3],
[4,5,6],
[7,8,9]];
Now, I need to update the list, let's say the user wants to change element at NL[1][1] (i.e. 5) to 'X'.
NL will be updated as
NL = [[1,2,3],
[4,'X',6],
[7,8,9]];`
I am having trouble trying to find the position of the element and then changing it. Any help is much appreciated.
Thanks
Using numpy:
NL = np.array(NL)
mask = np.where(NL == 5)
NL[mask] = 10
array([[ 1, 2, 3],
[ 4, 10, 6],
[ 7, 8, 9]])
Solution2:
def get_index(num, List):
for row, i in enumerate(List):
if num in i:
return row, i.index(num)
return -1
idx = get_index(5,NL)
if idx>0:
NL[idx[0]][idx[1]] = 7
[[1, 2, 3], [4, 7, 6], [7, 8, 9]]
Use 2 indexes, 1 for the what nested list you want and one for what element of the nested list you want.
So in this case you want the 2nd list's 2nd element:
NL[1][1]='X'
Output:
[[1, 2, 3], [4, 'X', 6], [7, 8, 9]]
Let's say you need to find the element 5 and want to replace it with 10.
We iterate through the outer list and then each inner-list's elements. Once we find the element we look for, we can replace it by the indexes. We use enumerate to have the indexes once we find a matching element.
The following code replaces ALL matching elements (all occurences of 5).
NL = [[1,2,3], [4,5,6], [7,8,9]]
print(NL) # prints: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for i, sublist in enumerate(NL):
for y, element in enumerate(sublist):
if element == 5:
NL[i][y] = 10
print(NL) # prints: [[1, 2, 3], [4, 10, 6], [7, 8, 9]]
This will replace only the first occurrence of item_to_replace. If you want it to replace in all sublist then remove the break statement from try block.
item_to_replace = 5
for lst in NL:
try:
index = lst.index(item_to_replace)
lst[index] = # your replacement for item_to_replace
break
except ValueError:
continue
You should access to element by indexes. You have 2D list (array) so you should use 2 indexes: NL[1][1] = "X".
Complete code:
NL = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
print("Original: {}".format(NL))
NL[1][1] = "X"
print("New: {}".format(NL))
Output:
>>> python3 test.py
Original: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
New: [[1, 2, 3], [4, 'X', 6], [7, 8, 9]]
just use NL[1][1] = 'X'
then print(NL)
I am having trouble trying to find the position of the element and then changing it.
Most of the answers here seem to have missed that part, and assumed you had the position.
You can use a nested list comprehension:
NL = [[1,2,3],
[4,5,6],
[7,8,9]]
NL = [['X' if i==5 else i for i in j] for j in NL]
print(NL)
Output:
[[1, 2, 3],
[4,'X',6],
[7, 8, 9]]
How do I slice a list to get rid of "Hello","World" and "Monty" in each list of lists?
I may have worded that incorrectly, but this is what I mean:
lst1 = [["Hello", 1,2,3], ["World",4,5,6],["Monty",7,8,9]]
And I want to get this:
lst2 = [[1,2,3],[4,5,6],[7,8,9]]
Thank you for your help.
You can get a slice of a list lst starting with the second element using lst[1:]. To do it for each sublist you can use a list comprehension:
>>> lst1 = [["Hello", 1, 2, 3], ["World", 4, 5, 6], ["Monty", 7, 8, 9]]
>>> lst2 = [lst[1:] for lst in lst1]
>>> lst2
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
You can reach it with a list comprehension and get in each iteration the last elements beside the first of the nested list by using the [1:] selector.
lst1 = [["Hello", 1,2,3], ["World",4,5,6],["Monty",7,8,9]]
lst2 = [item[1:] for item in lst1]
print (lst2)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
I have the following list:
list = [[1, 2], [3, 4], [5, 6]]
How can I reverse each sublist? i.e
list = [[2, 1], [4, 3], [6, 5]]
Use a list comprehension:
[sublist[::-1] for sublist in outerlist]
Demo:
>>> outerlist = [[1, 2], [3, 4], [5, 6]]
>>> [sublist[::-1] for sublist in outerlist]
[[2, 1], [4, 3], [6, 5]]
This produces a new list. You can also reverse sublists in place by calling the list.reverse() method on each one in a loop:
for sublist in outerlist:
sublist.reverse()
The comprehension and slice syntax is great, but if you want the result to happen in-place with the same outer list, I suggest this might be more readable:
for elem in outerlist:
elem.reverse()