By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,550 Members | 1,189 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,550 IT Pros & Developers. It's quick & easy.

How to break down a python list

P: 27
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!
Nov 24 '10 #1
Share this Question
Share on Google+
4 Replies


P: 27
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!
Nov 24 '10 #2

Expert 100+
P: 621
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.
Expand|Select|Wrap|Line Numbers
  1. test_list = range(1, 51)
  2. for outer in range(0, len(test_list), 5):
  3.     total = 0
  4.     for inner in range(5):
  5.         total += test_list[outer+inner]
  6.         print test_list[outer+inner],
  7.     print "\n", float(total)/5 
Nov 24 '10 #3

P: n/a
omg, awful!

Expand|Select|Wrap|Line Numbers
  1. lambda lst, ln: [ lst[i:i+ln] for i in range(0, len(lst), ln) ]
Nov 24 '10 #4

bvdet
Expert Mod 2.5K+
P: 2,851
What's the lambda for?

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

Post your reply

Sign in to post your reply or Sign up for a free account.