请问我如何循环嵌套列表获取一个嵌套的元组列表,例如循环通过pot来获取rslt
pot = [[1,2,3,4],[5,6,7,8]]
我试过
b = []
for i in pot:
for items in i:
b = zip(pot[0][0:],pot[0][1:])
但没有得到所需的输出谢谢
期望结果=
rslt = [[(1,2),(3,4)],[(5,6),(7,8)]]
答案 0 :(得分:2)
根据grouper
recipe in the itertools documentation,您可以尝试这样的事情(假设您的子列表是您指定的长度):
>>> def grouper(iterable, n):
args = [iter(iterable)] * n # creates a list of n references to the same iterator object (which is exhausted after one iteration)
return zip(*args)
现在你可以测试一下:
>>> pot = [[1,2,3,4],[5,6,7,8]]
>>> rslt = []
>>> for sublist in pot:
rslt.append(grouper(sublist, 2))
>>> rslt
[[(1, 2), (3, 4)], [(5, 6), (7, 8)]]
答案 1 :(得分:1)
你也可以使用列表理解:
[[(a, b), (c, d)] for a, b, c, d in l]