我有一个像;
这样的清单list=[['1,2,3'], ['1,2'], ['1,2,3'], [1.0], [5.0]]
我想迭代它以获取每个元素的索引值,如下所示;
orig_list=[1,2,3,1,2,1,2,3,1,5]
index_list=[1,1,1,2,2,3,3,3,4,5]
(索引从1开始)
答案 0 :(得分: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)
这就是你问的问题?
编辑:如果您的索引需要从1开始,那么每个索引只需+ 1
indexs = [list_.index(x) for x in list_]
答案 1 :(得分:0)
您的数据模型有点奇怪。列表只包含一个元素,即字符串或浮点数。我的回答适用于那个奇怪的案例。
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)
结果:
[1, 2, 3, 1, 2, 1, 2, 3, 1, 5]
[1, 1, 1, 2, 2, 3, 3, 3, 4, 5]
enumerate
为您提供索引(从1开始)。根据类型,split + convert to int,或者只转换为float。并创建一个相同索引的列表,或者只是附加当前索引。
答案 2 :(得分: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.