我该如何转换:
(1, 315.0, 2, 30.399999618530273, 3, 1.1033999919891357, 4, 8.0)
Run Code Online (Sandbox Code Playgroud)
进入这个:
((1, 315.0), (2, 30.399999618530273), (3, 1.1033999919891357), (4, 8.0))
Run Code Online (Sandbox Code Playgroud)
是否有一种简单的方法可以在没有循环的情况下完成它?
Fre*_*Foo 16
>>> x = (1, 315.0, 2, 30.399999618530273, 3, 1.1033999919891357, 4, 8.0)
>>> tuple(zip(x[::2], x[1::2]))
((1, 315.0), (2, 30.399999618530273), (3, 1.1033999919891357), (4, 8.0))
Run Code Online (Sandbox Code Playgroud)
Sve*_*ach 10
t = (1, 315.0, 2, 30.399999618530273, 3, 1.1033999919891357, 4, 8.0)
print tuple(zip(*[iter(t)] * 2))
Run Code Online (Sandbox Code Playgroud)
编辑:为了使这一点更具可读性,它或许应该封装在类似的功能grouper(),从功能itertools 的食谱:
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
Run Code Online (Sandbox Code Playgroud)