gpt4 book ai didi

python - 将嵌套列表转换为嵌套元组

转载 作者:行者123 更新时间:2023-11-30 23:25:55 24 4
gpt4 key购买 nike

请问我如何循环遍历嵌套列表以从中获取元组的嵌套列表,例如循环遍历 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)]]

最佳答案

基于石斑鱼 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)]]

关于python - 将嵌套列表转换为嵌套元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22761037/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com