Only create list in python with every 5th item? [duplicate]

微笑、不失礼 提交于 2019-12-11 04:24:21

问题


I have a list of 20 items. I want to create a new list than only contains every 5th item of the list.

Here is was I have:

    listA=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
    for i in len(range(listA)):
      print i

How can I create listB from listA using Python? listB should be equal to [5, 10, 15, 20].


回答1:


You can use this idiom

listB = listA[4::5]

This means starting from index 4, pick every 5th element.




回答2:


Another method is using the range() function to create a list of integers with increments (steps) of 5 between them, then using them to access the indexes of the original list to append them to a new one:

listB=[]
for i in range(4,len(listA),5):
    listB.append(listA[i])

The range(start, stop[, step]) function returns a list of integers, based on the arguments used:

  1. start - the first integer in the list (optional, defaults to 0).
  2. stop - the last integer generated in the list will be the greatest, but less than the value of stop (stop will not be in the list).
  3. step - the increment for values in the list (defaults to 1, can be made negative - to produce decreasing lists).


来源:https://stackoverflow.com/questions/40335148/only-create-list-in-python-with-every-5th-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!