How to iterate this kind of list?

Question:

How can I access the int value in a list that looks like this?

occurence_list = [["sleep", ["morning_meds", 2], ["watching_tv", 3]], ["morning_meds", ["sleep", 1], ["watching_tv", 3]]]
Asked By: Labarbona Dibaggio

||

Answers:

Assuming your list expands the same way as listed:

occurence_list = [["sleep", ["morning_meds", 2], ["watching_tv", 3]], ["morning_meds", ["sleep", 1], ["watching_tv", 3]]] 
for i in occurence_list:
    # On second and third there is a int.
    action = i[1][1]
    second_action = i[2][1]
    print(action,second_action) # 2 3 n 1 3
Answered By: annes

This is how you would print different aspect of this list:

occurence_list = [["sleep", ["morning_meds", 2], ["watching_tv", 3]], ["morning_meds", ["sleep", 1], ["watching_tv", 3]]] 
print[0][1]
>> ['morning_meds', 2]
print[0][1][1]
>> 2
Answered By: Kineye

There’s not much to go on based on your example. You would need to know the structure of the array to make a more informed decision. However, if you want to generalise the issue, saying that you have an arbirarily nested array, and you want to extract all integers, you could do this:

def get_ints(nested_list):
    for item in nested_list:
        if isinstance(item, list):
            yield from get_ints(item)
        if isinstance(item, int):
            yield item

ints = list(get_ints(occurence_list))

Output:

[2, 3, 1, 3]
Answered By: tituszban

If you want a listing of the int values one of unlimited number of options doing this will be:

occurrence_list = [["sleep", ["morning_meds", 2], ["watching_tv", 3]], ["morning_meds", ["sleep", 1], ["watching_tv", 3]]] 
index_of_int = 1
for occurrence in occurrence_list:
    txt, list_1, list_2 = occurrence
    print(list_1[index_of_int], list_2[index_of_int])
# prints: 
#         2 3
#         1 3

To get a better overview of the nested list structure as with print you can use pprint with 4 spaces indentation:

import pprint
pprint.pprint(occurrence_list, indent=4)
pprint_output = """
[   ['sleep', ['morning_meds', 2], ['watching_tv', 3]],
    ['morning_meds', ['sleep', 1], ['watching_tv', 3]]] 
"""

or use the not in Python distribution included pandas module:

import pandas as pd
df = pd.DataFrame(occurrence_list)
print(df)
pandas_df_print = """
              0                  1                 2
0         sleep  [morning_meds, 2]  [watching_tv, 3]
1  morning_meds         [sleep, 1]  [watching_tv, 3]
"""

From the nested list overview you can see how deep you need to nest indices to obtain a single value from a nested list. Each list within list element require further index. This is how it comes that to get the 1 in ['sleep', 1] you need three indices: occurrence_list[1][1][1]. The first two indices of an integer value you can take from the pandas dataframe print output (first index is the index of the row, second of the column) with printed indices for rows and columns.

You can check in code if your guess about the right indexing was OK with:

assert occurrence_list[1][1][1] == 1

which will give an assertion error if the indices don’t lead to the given specified value.

If you want to extract all integer values from a nested list you will find the code for it in the answer posted by tituszban.

Answered By: Claudio
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.