0

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)

4
  • 1
    Indexes start at 0, did you mean [0,0,0,1,1,2,2,2,3,4]? Commented Mar 17, 2017 at 12:26
  • 1
    What have you tried that didn't work ? Commented Mar 17, 2017 at 12:27
  • oh sry, the index needs to start from 1. Commented Mar 17, 2017 at 12:30
  • try to make a full question and ask for the specific problem next time Commented Mar 17, 2017 at 12:38

3 Answers 3

1
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_]
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0
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. 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.