简体   繁体   English

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

[英]using a for loop with xrange() on a multiple lists

I have the below code which assign a number to each item from list1 depending on len(list1): 我有以下代码,根据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))

The result will print as following: 结果将打印如下:

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

If i have a multiple lists: list2, list3, list4 如果我有多个列表:list2,list3,list4

How can i apply it to this code?.. 我如何将其应用于此代码?

Use 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')]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM