Hey all! This is my first post on Dani's Web but I have long before used it as a resource for understanding different problems I have encountered with Python. I have only just started learning Python so please excuse my lack of understanding on this problem.

counter = 0
nameList = []
ageList = []
averageAge = []

text_file = open("names.dat", "r")

while counter != 41:
    name = text_file.read(20)
    age = text_file.read(2)
    text_file.read(1)

    if age != '':
        nameList.append(name)
        ageList.append(int(age))
    
    counter += 1
    
text_file.close()


average = (sum(ageList )) / (len(ageList ))

print ("The names are: \n" , nameList)
print ("The ages are: \n" , ageList)
print ("The average is: \n" , average)

I wish to now expand on this code by making it search my ageList:

The ages are: 
 [23, 17, 26, 25, 45, 15, 37, 28, 42, 41, 12, 21, 58, 62, 19, 52, 34, 64, 56, 28, 16, 37, 91, 72, 31, 26, 36, 25, 42, 38, 25, 12, 29, 85, 45, 65, 65, 72, 49, 67]

From this, I want to determine what ages in that list are lower than the average. In this case, the average will be 40.825. Now I've tried using for and if loops to work around this but to no avail.

new_ageList = []
if age in ageList < average:
    new_ageList.append(age)

The above code is what I'm trying to achieve as I wish to the ones that are lower than the average to a new list.

Could someone please assist me. Cheers.

user45949219
Deleted Member

You can write

new_ageList = list()
for age in ageList:
    if age < average:
        new_ageList.append(age)

But it can be shortened using the list comprehension syntax:

new_ageList = [age for age in ageList if age < average]

Also it is generally better idea to keep information together. So you would have one info list with [[name, age], [othername, otherage] ....]

Your reading file by bytekinds is un-ideomatic, as I understand you have fixed lenght line of 20 for name and 2 for age. I would say like this:

# read lines stripping newlines
info = [line.rstrip() for line in open("names.dat") if line != '\n']
#process further
info = [[line[:20], int(line[20:])) for line in info]
#do calculations

Edited 5 Years Ago by pyTony: n/a

This article has been dead for over six months. Start a new discussion instead.