你可以在这里使用
zip
。
In [1]: a=[(1,2),(3,4),(5,6)]
In [2]: x,y=zip(*a)
In [3]: x
Out[3]: (1, 3, 5)
In [4]: y
Out[4]: (2, 4, 6)
In [5]: min(x),max(x)
Out[5]: (1, 5) #1 in min and 5 is max in x
In [6]: min(y),max(y)
Out[6]: (2, 6) #2 is min and 5 is max in y
在谷歌Colab上进行
timeit
分析。
%timeit minmax(z) #ch3ster's answer
1 loop, best of 3: 546 ms per loop
%timeit minmax1(z) #CDJB's answer
1 loop, best of 3: 1.22 s per loop
%timeit minmax2(z) #Mihai Alexandru-Ionut's answer
1 loop, best of 3: 749 ms per loop
%timeit minmax3(z) #Yevhen Kuzmovych's answer
1 loop, best of 3: 1.59 s per loop
编辑: 如果我们在这里使用set
,仍然可以减少执行时间。
In [24]: def minmax(a):
...: x=set()
...: y=set()
...: for i,j in a:
...: x.add(i)
...: y.add(j)
...: return max(x),min(x),max(y),min(y)
一个包含3百万或30万个元素的元组列表用于基准测试。
z=[(randint(0,10),randint(0,10)) for _ in range(3000000)]
timeit
是 Python 3.7 和 Windows 10 中进行性能分析的工具。
In [25]: timeit minmax(z) #Ch3steR's set answer.
384 ms ± 26.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [44]: timeit minmax1(z) #Ch3steR's zip answer.
626 ms ± 3.28 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [39]: timeit minmax2(z) #CDJB's answer max with lambda
1.18 s ± 25.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [40]: timeit minmax3(z) #Mihai Alexandru-Ionut's answer max with itemgetter
739 ms ± 42.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [41]: timeit minmax4(z) #Yevhen Kuzmovych's answer with updating max and min while iterating
1.97 s ± 42.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Ch3steR的设定答案 < Ch3steR的压缩答案 < Mihai Alexandru-Ionut的使用itemgetter的最大值和最小值 < CDJB的使用lambda的最大值和最小值 < Yevhen Kuzmovych的在迭代时更新最大值和最小值的答案
当 0<= x,y <=1000000
时
用于基准测试的列表。
x=[(randint(0,1000000),randint(0,1000000)) for _ in range(3000000)]
< p >使用
timeit
进行分析。
In [48]: timeit minmax(x) #Ch3steR's set answer.
1.75 s ± 92.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [49]: timeit minmax1(x) #Ch3steR's zip answer.
753 ms ± 31.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [51]: timeit minmax2(x) #CDJB's answer max with lambda
1.29 s ± 115 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [52]: timeit minmax3(x) #Mihai Alexandru-Ionut's answer max with itemgetter
794 ms ± 35.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [53]: timeit minmax4(x) #Yevhen Kuzmovych's answer with updating max and min while iterating
2.3 s ± 164 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
注意:
当0< x,y <10
时,Ch3steR的方案是高效的,但当0< x,y <1000000
时,它的平均时间为1.7秒
。
我强烈建议在0< x,y < 1000000
时使用Ch3steR的zip方案或Mihai Alexandru-Ionut的max和min with itemgetter方案。