Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding average length of items in a list. Python

my_list = [['abcdefg','awdawdawd'],['awdwer'],[],'rtgerfwed','wederfrtg']]

so i have a list and i want to find the average lengths for each sublist within the list

i tried this but it didn't seem to work

lengths = []
lengths = my_list

for k in lengths:
    k = len(k)

print lengths

# i get this again -> [['abcdefg','awdawdawd'],['awdwer'],[],'rtgerfwed','wederfrtg']]

i want the output to be

lengths = [8,6,0,9]
like image 697
O.rka Avatar asked Mar 09 '26 14:03

O.rka


2 Answers

A list of the lengths of each element in a list:

lengths = [len(i) for i in my_list]

For the average:

def averageLen(lst):
    lengths = [len(i) for i in lst]
    return 0 if len(lengths) == 0 else (float(sum(lengths)) / len(lengths)) 

If it's a list of lists:

lengths = [averageLen(i) for i in my_list]
like image 172
Rushy Panchal Avatar answered Mar 11 '26 09:03

Rushy Panchal


First, iterating over a list in python only copies the value of each item into a temporary variable. So in fact, in your example, k is assigned a value of each item in the list, but changing it doesn't change the original list. Second, it seems that you tried to map each item in the list to its length, and not to the average length of its items. Mapping each item to its length could be easily done with the builtin function map: map(len,lengths). However, to accomplish what you request, we're gonna need to improve a little bit. Let's define a function to calculate the average length of a lists items:

def average_len(l):
  return sum(map(len, l))/float(len(l))

Now we can use map again to get the average of each sublist: map(average_len, lengths).

like image 34
ehudt Avatar answered Mar 11 '26 09:03

ehudt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!