Python 将嵌套列表转换为元组

Python 将嵌套列表转换为元组,python,python-3.x,Python,Python 3.x,如何在不导入任何模块的情况下将嵌套列表分组为三个元组。请显示扩展的for循环,以便我更好地理解它。 例如,我想要这个嵌套列表。请注意,这将始终是 3个子列表,因此没有索引错误。 谢谢 [[1], [2], [3], [4], [5], [6], [7], [8], [9]] # Given [(1, 2, 3), (4, 5, 6), (7, 8, 9)] # Result Wanted 不需要索引。您可以在迭代器上使用next(),甚至在for循环中: xss = [[1], [2], [

如何在不导入任何模块的情况下将嵌套列表分组为三个元组。请显示扩展的for循环,以便我更好地理解它。 例如,我想要这个嵌套列表。请注意,这将始终是 3个子列表,因此没有索引错误。 谢谢

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

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

不需要索引。您可以在迭代器上使用
next()
,甚至在for循环中:

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

您可以使用步长为3的切片和压缩来生成三元组,在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))

你想用什么语言来做这件事?JavaScript?PHP?@dylanjameswagner你看到Python标签了吗?@SportsPlanet收到答案后,请不要编辑你的问题来彻底改变你的提问。尤其是不要改变你所问的语言;这样做将使现有的Python答案无效,这在堆栈溢出上是不允许的。@gilch,ohp,不,我没有。他说,也许有一条没有next()的路,还有iter(xss),也许还有一条更长的路?

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)