A simple understanding of the dictionary should do the trick:
{key: [index for index, x in enumerate(my_list) if x == key] for key in my_list}
Simple procedure:
>>>> my_list = ['A','B','A','B']
>>>> {key: [index for index, x in enumerate(my_list) if x == key] for key in my_list}
>>>> {'A': [0, 2], 'B': [1, 3]}
How it works
The list of concepts is often used in Python as syntactic sugar for the for loop. Instead of writing
my_list = []
for item in range(10):
my_list.append(item)
:
my_list = [item for item in range(10)]
, , , . - , , - .
. , , , .
:
{k: None for k in ["Hello", "Adele"]}
>>>> {"Hello": None, "Adele": None}
, , ,
, :
my_dict = {}
for key in my_list:
indices = []
for index,value in enumerate(my_list):
if value == key:
indices.append(index)
my_dict[key] = indices
enumerate , . , .
:
enumerate(['a','b','a','b'])
>>>> [(0,'a'),(1,'b'),(2,'b'),(3,'b')]
enumerate.
, - . , : . - , . .
. @wilinx . @Rob set(my_list), .