虽然我喜欢Dikei 的清晰和简洁的回答,但我仍然认为一个好的选择很简单:
for sublist in mylist:
item = sublist[1]
...
do_stuff(item)
...
do_other_stuff(item)
...
它仍然很清楚,可以扩展为更容易做,并且可能是最快的。
这里有一些快速测试——由于在循环中什么都不做,我不确定它们的准确度,但它们可能会给出一个想法:
python -m timeit -s "mylist = [range(1,8) for _ in range(1,8)]" 'for thing in mylist:' ' item=thing[1]' ' pass'
1000000 loops, best of 3: 1.25 usec per loop
python -m timeit -s "mylist = [range(1,8) for _ in range(1,8)]" 'for thing in (i[1] for i in mylist):' ' pass'
100000 loops, best of 3: 2.37 usec per loop
python -m timeit -s "mylist = [range(1,8) for _ in range(1,8)]" 'for thing in itertools.islice(itertools.chain(*mylist),1,None,len(mylist)):' ' pass'
1000000 loops, best of 3: 2.21 usec per loop
python -m timeit -s "import numpy" -s "mylist = numpy.array([range(1,8) for _ in range(1,8)])" 'for thing in mylist[:,1]:' ' pass'
1000000 loops, best of 3: 1.7 usec per loop
python -m timeit -s "import numpy" -s "mylist = [range(1,8) for _ in range(1,8)]" 'for thing in numpy.array(mylist)[:,1]:' ' pass'
10000 loops, best of 3: 63.8 usec per loop
请注意,如果一旦生成 numpy 会很快,但对于单个操作按需生成则非常慢。
在大型列表中:
python -m timeit -s "mylist = [range(1,100) for _ in range(1,100)]" 'for thing in mylist:' ' item=thing[1]' ' pass'
100000 loops, best of 3: 16.3 usec per loop
python -m timeit -s "mylist = [range(1,100) for _ in range(1,100)]" 'for thing in (i[1] for i in mylist):' ' pass'
10000 loops, best of 3: 27 usec per loop
python -m timeit -s "mylist = [range(1,100) for _ in range(1,100)]" 'for thing in itertools.islice(itertools.chain(*mylist),1,None,len(mylist)):' ' pass'
10000 loops, best of 3: 101 usec per loop
python -m timeit -s "import numpy" -s "mylist = numpy.array([range(1,100) for _ in range(1,100)])" 'for thing in mylist[:,1]:' ' pass'
100000 loops, best of 3: 8.47 usec per loop
python -m timeit -s "import numpy" -s "mylist = [range(1,100) for _ in range(1,100)]" 'for thing in numpy.array(mylist)[:,1]:' ' pass'
100 loops, best of 3: 3.82 msec per loop
请记住,速度应该始终排在可读性之后,除非您真的需要它。