-2

have a list of 20 items. I want to create a new list than only contain the max value of every five items.

Here is was I have:

listA = [1,2,23,4,5,6,7,40,9,10,100,12,13,14,15,700,17,18,19,20]
for i in len(range(listA):
    print i

How can I create listB = [23, 40, 100, 700] from listA using Python?

Julien
  • 13,986
  • 5
  • 29
  • 53
airzinger1
  • 151
  • 9
  • 1
    It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [FAQ](http://stackoverflow.com/tour) and [How to Ask](http://stackoverflow.com/questions/how-to-ask). – TigerhawkT3 Oct 31 '16 at 02:08
  • 2
    You already asked here how to get every 5th item: http://stackoverflow.com/questions/40335148/only-create-list-in-python-with-every-5th-item what is the problem now? – Dekel Oct 31 '16 at 02:11
  • `max(listA[:5])`, `max(listA[5:10])`, etc., `max(listA[5*n:5*(n+1)])` – furas Oct 31 '16 at 02:12

1 Answers1

1

To get 5 elements you can use listA[:5], listA[5:10], etc., listA[5*n:5*n+5]

listA = [1,2,23,4,5,6,7,40,9,10,100,12,13,14,15,700,17,18,19,20]

for i in range(0, len(listA), 5):
    print(max(listA[i:i+5]))

Or using generator

def chunk(lst, size):
    for i in range(0, len(lst), size):
        yield lst[i:i+size]

for x in chunk(listA, 5):
    print(max(x))
furas
  • 134,197
  • 12
  • 106
  • 148