假设我们有一个从0到1000的数字列表。是否有一种python式的/有效的方法来生成第一个和后续的第10项的列表,即[0,10,20,30,…]] ?
是的,我可以使用for循环来做到这一点,但我想知道是否有一种更整洁的方法来做到这一点,也许甚至在一行中?
假设我们有一个从0到1000的数字列表。是否有一种python式的/有效的方法来生成第一个和后续的第10项的列表,即[0,10,20,30,…]] ?
是的,我可以使用for循环来做到这一点,但我想知道是否有一种更整洁的方法来做到这一点,也许甚至在一行中?
当前回答
你可以像这样使用切片操作符:
l = [1,2,3,4,5]
l2 = l[::2] # get subsequent 2nd item
其他回答
existing_list = range(0, 1001)
filtered_list = [i for i in existing_list if i % 10 == 0]
你可以像这样使用切片操作符:
l = [1,2,3,4,5]
l2 = l[::2] # get subsequent 2nd item
使用范围(start, end, step)
li = list(range(0, 1000, 10))
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90 ... 990]
或者,如果你有一个列表,使用slice: From manual: s[i:j:k] slice of s From i to j, step k
yourlist = [0, ... ,10 ...]
sub = yourlist[::10] # same as yourlist[0:100:10]
>>> sub
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
>>> lst = list(range(165))
>>> lst[0::10]
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160]
注意,这比循环检查每个元素的模量快100倍左右:
$ python -m timeit -s "lst = list(range(1000))" "lst1 = [x for x in lst if x % 10 == 0]"
1000 loops, best of 3: 525 usec per loop
$ python -m timeit -s "lst = list(range(1000))" "lst1 = lst[0::10]"
100000 loops, best of 3: 4.02 usec per loop
Source_list[::10]是最明显的,但这对任何可迭代对象都不起作用,对于大型列表内存效率也不高。 itertools。islice(source_sequence, 0, None, 10)适用于任何可迭代对象,并且是内存高效的,但对于大列表和大步骤可能不是最快的解决方案。 (source_list[i] for i in xrange(0, len(source_list), 10))