I need to keep my data in a list of lists, but want to edit elements in the lists based on their overall position.
For instance:
JavaScript
x
2
1
mylist = [['h','e','l','l','o'], ['w','o','r','l','d']]
2
I want to change position 5 as if it was all one list resulting in:
JavaScript
1
2
1
[['h','e','l','l','o'], ['change','o','r','l','d']]
2
This is for very large lists and lots of mutations so speed is essential!
Advertisement
Answer
Here is the solution of your’s question
JavaScript
1
24
24
1
# initializing list
2
input_list = [['h', 'e', 'l', 'l', 'o'], ['w', 'o', 'r', 'l', 'd']]
3
4
print("The initial list is : " + str(input_list))
5
6
length: int = 0
7
8
# define position(global index) where you want to update items in list
9
change_index = 5
10
11
## global starting index of sublist [0,5]
12
sub_list_start_index: list = list()
13
14
for sub_list in input_list:
15
sub_list_start_index.append(length)
16
length += len(sub_list)
17
18
# check if index we want to change is <= global list index and
19
if change_index <= length - 1 and change_index >= max(sub_list_start_index):
20
sub_list_index = int(change_index - max(sub_list_start_index))
21
input_list[input_list.index(sub_list)][sub_list_index] = 'change'
22
23
print("Updated list : " + str(input_list))
24
Output:
JavaScript
1
3
1
The initial list is : [['h', 'e', 'l', 'l', 'o'], ['w', 'o', 'r', 'l', 'd']]
2
Updated list : [['h', 'e', 'l', 'l', 'o'], ['change', 'o', 'r', 'l', 'd']]
3