在多个列表上使用带有xrange()的for循环

时间:2016-05-12 20:17:12

标签: python list tuples itertools

我有以下代码,它根据len(list1)为list1中的每个项目分配一个数字:

list1 = ["a", "b", "c", "d"]
result = []

for i in xrange(0, len(list1)):
    result += (str(i+1), list1[i], )

new_result = list(izip(*[iter(result)]*2))

结果将打印如下:

[("1", "a"), ("2", "b"), ("3", "c"), ("4", "d")]

如果我有多个列表:list2,list3,list4

如何将其应用于此代码?..

1 个答案:

答案 0 :(得分:1)

使用List Comprehensions

lists = [   ["a", "b", "c", "d"],   # list1
            ["e", "f", "g", "h"]]   # list2

new_results = [[(str(idx), x) for idx, x in enumerate(l, 1)] for l in lists]
print(new_results)

# Output
[[('1', 'a'), ('2', 'b'), ('3', 'c'), ('4', 'd')], [('1', 'e'), ('2', 'f'), ('3', 'g'), ('4', 'h')]]