如何在将每个元组拆分为头和尾的同时迭代[(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。
答案 0 :(得分: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)