How to break down a python list

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ronparker
    New Member
    • Aug 2010
    • 27

    How to break down a python list

    Hello all!

    I have a variable name "thelist" which is a list of 100,000 elements. I was wondering how I can make two new lists of the average value and standard deviation from this. For example if my list is [1,2,3,4,5,6,7,8 ,9,10] then the new list would be the average of the every 5 numbers, endeing up looking like [average(1,2,3,4 ,5),average(6,7 ,8,9,10)]=[3,8]. I am very comfortable using numpy to get the average and standard deviation values. I am just having trouble breaking the initial list down. I'm not sure if this is what indexing is.

    Any help would really be appreciated,
    Thank YOU!
  • ronparker
    New Member
    • Aug 2010
    • 27

    #2
    I am also curious to know if there is a simple way to see how many positive numbers there are in each 100 segments of the bit 100,000 list. Thank YOU!

    Comment

    • dwblas
      Recognized Expert Contributor
      • May 2008
      • 626

      #3
      For example if my list is [1,2,3,4,5,6,7,8 ,9,10] then the new list would be the average of the every 5 numbers
      You can use two for loops. With the outer loop, set the step value at 5 or whatever the increment. The inner loop adds each of the 5 numbers together.
      Code:
      test_list = range(1, 51)
      for outer in range(0, len(test_list), 5):
          total = 0
          for inner in range(5):
              total += test_list[outer+inner]
              print test_list[outer+inner],
          print "\n", float(total)/5

      Comment

      • Andrew Grigorev

        #4
        omg, awful!

        Code:
        lambda lst, ln: [ lst[i:i+ln] for i in range(0, len(lst), ln) ]
        Last edited by bvdet; Nov 25 '10, 12:31 AM. Reason: Please use code tags when posting code. [code]....code goes here....[/code]

        Comment

        • bvdet
          Recognized Expert Specialist
          • Oct 2006
          • 2851

          #5
          What's the lambda for?

          Code:
          >>> data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
          >>> n = 5
          >>> def average(seq):
          ... 	return sum(seq)/float(len(seq))
          ... 
          >>> [average(data[i:i+n]) for i in range(0, len(data), n)]
          [3.0, 8.0, 13.0]
          >>> data = [1,2,-3,4,5,6,-7,8,-9,10,11,-12,-13,-14,15]
          >>> [sum([1 for item in data[i:i+n] if item>0]) for i in range(0, len(data), n)]
          [4, 3, 2]
          >>>

          Comment

          Working...