Reputation: 135
I have a list like;
list=[['1,2,3'], ['1,2'], ['1,2,3'], [1.0], [5.0]]
I would like to iterate through it to obtain the index value for each element, something like this;
orig_list=[1,2,3,1,2,1,2,3,1,5]
index_list=[1,1,1,2,2,3,3,3,4,5]
(with indexes starting at 1)
Upvotes: 0
Views: 5034
Reputation: 209
list_=[['1,2,3'], ['1,2'], ['1,2,3'], [1.0], [5.0]]
orig_list = []
index_list = []
for x in list_:
for y in x.split(","): #You can make a list out of a string with split functions.
index_list.append(list_.index(x)+1)
orig_list.append(float(y)) #Because you have floats and int in the strings I would convert them both to float.
Upvotes: 0
Reputation: 140307
Your data model is a bit strange. Lists containing only one element, being string or float. My answer applies to that strange case.
l=[['1,2,3'], ['1,2'], ['1,2,3'], [1.0], [5.0]]
orig_list=[]
index_list=[]
for i,item in enumerate(l,1):
if isinstance(item[0],str):
toks = [int(x) for x in item[0].split(",")]
orig_list+=toks
index_list+=[i]*len(toks)
else:
orig_list.append(int(item[0]))
index_list.append(i)
print(orig_list)
print(index_list)
results in:
[1, 2, 3, 1, 2, 1, 2, 3, 1, 5]
[1, 1, 1, 2, 2, 3, 3, 3, 4, 5]
enumerate
gives you the index (start at 1). Depending on the type, either split + convert to int, or just convert to float. And create a list of the same index, or just append the current index.
Upvotes: 0
Reputation: 1425
list_=[['1,2,3'], ['1,2'], ['1,2,3'], [1.0], [5.0]]
for x in list_:
index_ = list_.index(x)
for x in list_:
for y in x:
index_ = list_.index(y)
Ii this what you was asking?
EDIT: if your index needs to start at one then simply + 1 to each index
indexs = [list_.index(x) for x in list_]
Upvotes: 1