使用尾元组的变量遍历元组列表

2024-05-14 12:57:49 发布

您现在位置:Python中文网/ 问答频道 /正文

如何迭代[(1,2,3), (2,3,1), (1,1,1)],同时将每个元组分成一个头部和一个尾部? 我在用一种类似于Python的方式:

for h, *t in [(1,2,3), (2,3,1), (1,1,1)]:
    # where I want t to be a tuple consisting of the last two elements
    val = some_fun(h)
    another_fun(val, t)

上面的内容不适用于Python2.7。你知道吗


Tags: oftoinfor方式valbewhere
1条回答
网友
1楼 · 发布于 2024-05-14 12:57:49

您可以使用map来列出和切片:

for h, t in map(lambda x: (x[0], x[1:]), [(1,2,3), (2,3,1), (1,1,1)]):
    print("h = %s, t=%s"%(h, t))
#h = 1, t=(2, 3)
#h = 2, t=(3, 1)
#h = 1, t=(1, 1)

相关问题 更多 >

    热门问题