Home > Enterprise >  How to group by nested list index
How to group by nested list index

Time:08-04

I have indexes in a nested list

[[1],[2,3][4,5,6]]

and I have list of elements

['A','B','C','D','E','F']

I want to group by the indexes meanining the output would look like this:

[['A'],['B','C']['D','E','F']]

CodePudding user response:

You can use nested for loops (but be aware that indexing in python starts with 0):

elements = ['A', 'B', 'C', 'D', 'E', 'F']
index = [[0], [1, 2], [3, 4, 5]]
new = []

for i in index:
    temp = []
    for j in i:
        temp.append(elements[j])
    new.append(temp)

print(new)

Result:

[['A'], ['B', 'C'], ['D', 'E', 'F']]

CodePudding user response:

Erna's answer works if you know how nested the index list is. If you don't, you can use a recursive function:

def group(el, ind):
    ret = []
    for i in ind:
        if isinstance(i, int):
            ret.append(el[i])
        else:
            ret.append(group(el, i))
    return ret

elements = ['A', 'B', 'C', 'D', 'E', 'F']
index = [[0], [1, 2], [3, 4, 5]]

print(group(elements, index))

Output: [['A'], ['B', 'C'], ['D', 'E', 'F']]

CodePudding user response:

indices = [[1], [2, 3], [4, 5, 6]]
elements = ['A','B','C','D','E','F']

[[elements[i - 1] for i in sublist] for sublist in indices]

# [['A'], ['B', 'C'], ['D', 'E', 'F']]

CodePudding user response:

Function (with recursion):

def nested_sort(user_indexes, user_list):
    result = []
    if isinstance(user_indexes, list) and isinstance(user_list, list):
        for user_index in user_indexes:
            if isinstance(user_index, int):
               result.append(user_list[user_index])
            elif isinstance(user_index, list):
               result.append(nested_sort(user_index, user_list))    
    return result

Example 1.

Input:

user_indexes = [[1],[2,3],[4,5,6]]
user_list = ['A','B','C','D','E','F','G','H']
nested_sort(user_indexes, user_list)

Output:

[['B'], ['C', 'D'], ['E', 'F', 'G']]

Example 2.

Input:

user_indexes = [[1],[2,[3]],[4,[5,[6]]]]
user_list = ['A','B','C','D','E','F','G','H']
nested_sort(user_indexes, user_list)

Output:

[['B'], ['C', ['D']], ['E', ['F', ['G']]]]
  • Related