Nested List Indices

Create list of strings from nested list of indices and nested list of strings

Use:

  • zip to pair corresponding sublists in both nested lists
  • list comprehension to get the corresponding values from paired sublists

Code

new_list = [[vals[i] for i in idxs] for idxs, vals in zip(nested_indices, strings_list)]

Result

[['0d', '0e', '0f'], ['1a', '1b', '1c'], ['2g', '2g', '2h']]

Dynamic get nested list according to index

How about something like this:

a = [[[["test"], ["test1"]], ["test2"]], ["test3", "test4"]]
b = [0, 1, 0]

item = a
for i in b:
item = item[i]
print(item) # test2

Nested List Indices

The problem is caused by the fact that python chooses to pass lists around by reference.

Normally variables are passed "by value", so they operate independently:

>>> a = 1
>>> b = a
>>> a = 2
>>> print b
1

But since lists might get pretty large, rather than shifting the whole list around memory, Python chooses to just use a reference ('pointer' in C terms). If you assign one to another variable, you assign just the reference to it. This means that you can have two variables pointing to the same list in memory:

>>> a = [1]
>>> b = a
>>> a[0] = 2
>>> print b
[2]

So, in your first line of code you have 4 * [0]. Now [0] is a pointer to the value 0 in memory, and when you multiply it, you get four pointers to the same place in memory. BUT when you change one of the values then Python knows that the pointer needs to change to point to the new value:

>>> a = 4 * [0]
>>> a
[0, 0, 0, 0]
>>> [id(v) for v in a]
[33302480, 33302480, 33302480, 33302480]
>>> a[0] = 1
>>> a
[1, 0, 0, 0]

The problem comes when you multiply this list - you get four copies of the list pointer. Now when you change one of the values in one list, all four change together:

>>> a[0][0] = 1
>>> a
[[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]

The solution is to avoid the second multiplication. A loop does the job:

>>> some_list = [(4 * [0]) for _ in range(4)]

Index of an element in a nested list

Ajax1234's answer works, but if you need something a little more simple this may be better:

def find_idx(input_list, elem):
for i in range(len(input_list)):
if isinstance(input_list[i], list):
result = find_idx(input_list[i], elem)
if result:
return [i] + result
elif input_list[i] == elem:
return [i]

return False

input_list = [1, [5, 62, 6], 4, [99, [100, 200, 600, [1000, [2000]]]], [74, 41, 16], 7, [8], [[[400]]]]

print(find_idx(input_list, 2000))
# Output: [3, 1, 3, 1, 0]


This is basically a DFS (https://en.wikipedia.org/wiki/Depth-first_search). If you think of your data structure as a tree, your list entries are nodes since they themselves can contain other lists, just as a node in a tree can point to other nodes. The magic is in returning False if nothing was found at the very end of the method, but recursively searching all sublists before you get to that point. Also, you have to check whether your list entry is itself a list, but this is just an analogy to the fact that a tree can have nodes that do point to other nodes, and nodes that do not (leaf nodes, or plain old numbers in your case).

Find the values in a list using a nested list of indices?

Where you are using nested_list[0] you should use i; and then you should use another variable where you use i in the comprehension. Many errors hide in unclear variable naming; one should strive to make sure variable names always correctly identify their purpose. I would rewrite as follows:

values_from_list = []

for sublist in nested_list:
values_from_list.append([numbers[index] for index in sublist])
print(values_from_list)

or, more succintly,

values_from_list = [
[numbers[index] for index in sublist]
for sublist in nested_list
]

Accessing index of nested list passing single item in the index() method

You can make your own function that will mimic the .index() method. For example:

def my_index(lst, n):
for i, l in enumerate(lst):
if n in l:
return i
raise ValueError("{} not found".format(n))

print(my_index(points, 30))

Prints:

0

Or throws ValueError if n is not found (just as .index())

How to index into nested lists?

Think of it as a list of lists rather than a "matrix", and the logic becomes more obvious. Matrix m has two elements: m[0] = [1, 2, 3] and m[1] = [4, 5, 6]. So accessing a single value from within those lists requires another index. For example, m[0][1] = 2.

def matrix(m, a, b):
return m[a][b] # element b from list a in list m

If you really want to use a matrix, consider numpy.



Related Topics



Leave a reply



Submit