简体   繁体   English

将嵌套列表转换为元组

[英]Converting Nested List into Tuple

How can I take a nested List and group it into a tuple of three without importing any module.如何在不导入任何模块的情况下获取嵌套列表并将其分组为三个元组。 Please show the expanded for loops so I can understand it better.请显示扩展的 for 循环,以便我更好地理解它。 For example, I want this nested List.例如,我想要这个嵌套列表。 Note this will always multiples of 3 sub lists so there is not a index error.请注意,这将始终是 3 个子列表的倍数,因此不会出现索引错误。 Thankyou.谢谢你。

[[1], [2], [3], [4], [5], [6], [7], [8], [9]] # Given

[(1, 2, 3), (4, 5, 6), (7, 8, 9)] # Result Wanted

No need for indexes.不需要索引。 You can use next() on an iterator even inside a for loop:即使在 for 循环中,您也可以在迭代器上使用next()

xss = [[1], [2], [3], [4], [5], [6], [7], [8], [9]]
it = iter(xss)
answer = []
for x, in it:
    answer.append((x, next(it)[0], next(it)[0]))

You can slice with a step size of 3 and zip to make the triples, do a nested unpacking in the for loop, and rebuild the triples without the wrapping lists.您可以使用 3 步长和 zip 进行切片以制作三元组,在 for 循环中进行嵌套解包,并在没有包装列表的情况下重建三元组。

xss = [[1], [2], [3], [4], [5], [6], [7], [8], [9]]
it = zip(xss[::3], xss[1::3], xss[2::3])
answer = []
for [x], [y], [z] in it:
    answer.append((x, y, z))

given = [[1], [2], [3], [4], [5], [6], [7], [8], [9]]  # because this is a list within a list

output = []

for i in range(0, len(given),3): # step size 3 indicated
    temp = (given[i][0], given[i+1][0], given[i+2][0]) # therefore you need the "[0]" behind each given[i]
    output.append(temp)
print (output)

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

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