【问题标题】:Iterate over list of tuples using a variable for the tail tuple [duplicate]使用尾元组的变量迭代元组列表[重复]
【发布时间】:2019-03-29 00:16:17
【问题描述】:

如何迭代[(1,2,3), (2,3,1), (1,1,1)],同时将每个元组分成头部和尾部? 我正在寻找这样一种简洁的pythonic方式:

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)

以上不适用于 python 2.7。

【问题讨论】:

  • 尝试用括号括住h, *t,例如(h, *t)
  • @dcg 那也行不通。据我所知,Python 2 不支持这种解包。
  • The above doesn't work for python 2.7 哇。在这里学到了一些新东西。

标签: python python-2.7 for-loop tuples


【解决方案1】:

您可以使用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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-30
    • 2013-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多