440,550 Members | 1,189 Online
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
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 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  Nov 24 '10 #3

 P: n/a omg, awful! Expand|Select|Wrap|Line Numbers lambda lst, ln: [ lst[i:i+ln] for i in range(0, len(lst), ln) ] Nov 24 '10 #4

 Expert Mod 2.5K+ P: 2,851 What's the lambda for? Expand|Select|Wrap|Line Numbers >>> 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] >>>  Nov 25 '10 #5