Python nested lists

Can someone tell me how can I call indexes in a nested list?

Usually I just write:

for i in range (list) 

but what if I have a list with nested lists as shown below:

 Nlist = [[2,2,2],[3,3,3],[4,4,4]...] 

and I want to view the indices of each of them individually?

+10
source share
6 answers

If you really need indexes, you can just do what you said again for the internal list:

 l = [[2,2,2],[3,3,3],[4,4,4]] for index1 in xrange(len(l)): for index2 in xrange(len(l[index1])): print index1, index2, l[index1][index2] 

But it’s more logical to iterate over the list itself:

 for inner_l in l: for item in inner_l: print item 

If you really need indexes, you can also use enumerate :

 for index1, inner_l in enumerate(l): for index2, item in enumerate(inner_l): print index1, index2, item, l[index1][index2] 
+21
source

Try this setting:

 a = [["a","b","c",],["d","e"],["f","g","h"]] 

To print the second element in the first list ("b"), use print a[0][1] - for the second element in the 3rd list ("g"): print a[2][1]

The first brackets refer to a list of nested lists, the second pair refers to an element in this list.

+5
source

Can you do this. Adapt it to your situation:

  for l in Nlist: for item in l: print item 
+2
source

The title of the question is too broad, and the author needs more specific information. In my case, I needed to extract all the elements from a nested list, as in the example below :

Example:

 input -> [1,2,[3,4]] output -> [1,2,3,4] 

The code below gives me the result, but I would like to know if anyone can create a simpler answer:

 def get_elements_from_nested_list(l, new_l): if l is not None: e = l[0] if isinstance(e, list): get_elements_from_nested_list(e, new_l) else: new_l.append(e) if len(l) > 1: return get_elements_from_nested_list(l[1:], new_l) else: return new_l 

Method call

 l = [1,2,[3,4]] new_l = [] get_elements_from_nested_list(l, new_l) 
0
source
 n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]] def flatten(lists): results = [] for numbers in lists: for numbers2 in numbers: results.append(numbers2) return results print flatten(n) 

Conclusion: n = [1,2,3,4,5,6,7,8,9]

-1
source

I think you want to access list values ​​and their indices simultaneously and individually:

 l = [[2,2,2],[3,3,3],[4,4,4],[5,5,5]] l_len = len(l) l_item_len = len(l[0]) for i in range(l_len): for j in range(l_item_len): print(f'List[{i}][{j}] : {l[i][j]}' ) 
-1
source

Source: https://habr.com/ru/post/901844/


All Articles