在多个列表上使用带有 xrange() 的 for 循环
using a for loop with xrange() on a multiple lists
我有下面的代码,它根据 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
我如何将它应用到此代码?..
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')]]
我有下面的代码,它根据 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
我如何将它应用到此代码?..
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')]]