如何使用for循环索引列表?

时间:2017-02-04 01:30:19

标签: python list for-loop

我有一个单词列表。

mylist = ["aus","ausser","bei","mit","noch","seit","von","zu"]

我想将列表中的每个元素转换为子列表,并向每个元素添加一个数字,以便为每个条目编制索引。所以它应该输出

[[1, 'aus'], [2, 'ausser'], [3, 'bei'], [4, 'mit'], [5, 'noch'], [6, 'seit'], [7, 'von'], [8, 'zu']]

我知道如何用while循环

来做这件事
mylist = ["aus","ausser","bei","mit","noch","seit","von","zu","aus","ausser","bei","mit","noch","seit","von","zu","aus","ausser","bei","mit","noch","seit","von","zu"]

mylist2

i=0

while i <= 10:
    mylist2.append([i,mylist[i]])
    i = i +1

print(mylist2)

但我希望使用以下类型的结构for - 循环:

mylist = ["aus","ausser","bei","mit","noch","seit","von","zu"]

outlist =[[1,word] for word in mylist]
print(outlist)

我不确定如何使用for循环执行此操作。有人可以解释如何做到这一点?

4 个答案:

答案 0 :(得分:2)

如果您希望内部部分是列表,那么您可以将enumerate结果转换为列表理解中的列表:

>>> mylist = ["aus","ausser","bei","mit","noch","seit","von","zu"]
>>> [[idx, item] for idx, item in enumerate(mylist, 1)]
[[1, 'aus'],
 [2, 'ausser'],
 [3, 'bei'],
 [4, 'mit'],
 [5, 'noch'],
 [6, 'seit'],
 [7, 'von'],
 [8, 'zu']]

答案 1 :(得分:0)

使用enumerate

>>> mylist = ["aus","ausser","bei","mit","noch","seit","von","zu"]
>>> list(enumerate(mylist, 1))

[(1, 'aus'),
 (2, 'ausser'),
 (3, 'bei'),
 (4, 'mit'),
 (5, 'noch'),
 (6, 'seit'),
 (7, 'von'),
 (8, 'zu')]

如果您需要列表而不是元组,则可以

list(map(list(enumerate(mylist, 1))))

[[number, word] for number, word in enumerate(mylist, 1)]

答案 2 :(得分:0)

使用枚举:

[list(element) for element in list(enumerate(mylist, 1))]

答案 3 :(得分:0)

这是我认为您正在寻找的方法。

list1 = ["aus","ausser","bei","mit","noch","seit","von","zu"]
list2 = []
for i in range(len(list1)):
    list2 += [[i+1, list1[i]]]
print (list2)

使用for循环遍历列表1中的每个项目和列表1中的索引,并将索引添加1,使其不以0开头。