gpt4 book ai didi

python - 加速 Python 2.7 中的函数

转载 作者:行者123 更新时间:2023-11-28 22:53:59 25 4
gpt4 key购买 nike

我想知道是否有办法加快此处显示的功能。我知道这看起来不是很 pythonic...

def MakePairs(inputlist):
'''
@param inputlist: [[["a","b","c"],["d","e","f"]],[["g","h","i"],["j","k","l"]],...]
@return returnlist: [[["a","d"],["b","e],["c","f"]],[["g","j"],["h","k"],["i","l"]],...]
'''
returnlist = []
for Pair in xrange(len(inputlist)):
dummy2 = []
for item in xrange(len(inputlist[Pair][0])):
dummy = [Pair[0][item], Pair[1][item]]
dummy2.append(dummy)
returnlist.append(dummy2)

return returnlist

编辑:返回列表中的对必须是列表。

提前致谢!!!

最佳答案

看起来像 zip() 的工作:

>>> l = [[["a","b","c"],["d","e","f"]],[["g","h","i"],["j","k","l"]]]
>>> [zip(*item) for item in l]
[[('a', 'd'), ('b', 'e'), ('c', 'f')], [('g', 'j'), ('h', 'k'), ('i', 'l')]]

因此,您的函数将是:

def MakePairs(inputlist):
return [zip(*item) for item in inputlist]

另外,考虑使用 itertools.izip()而不是 zip()。

关于python - 加速 Python 2.7 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18624763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com