2

I am trying to write a loop in python that reads a text file of 50 numbers and sorts through the numbers and assigns them to different variables based on their values. I would like variable A to contain values less than 2, variable B to to contain values from 2 to 2.1, Variable c to contain values from 2.1 to 2.25, variable d to contain values from 2.25 to 2.5, and variable e to contain values from 2.25 to 2.5.

My code so far looks like this:

import os
import numpy
os.chdir('/Users/DevEnv')

dispFile = open('output1.txt')
displacement = dispFile.readlines()
dispFile.close()

displacement = [float(i.strip()) for i in displacement]


for i in range (0,50):
   displacementval = displacement[i]
   if i<2 displacementval()=a():

However, when I try to run this I get an invalid syntax error. I am new to python and programming and would appreciate any help!

user7269405
  • 59
  • 2
  • 8

5 Answers5

4

You need to initialize variables a, b, c, d, and e as list:

import os
import numpy
os.chdir('/Users/DevEnv')

dispFile = open('output1.txt')
displacement = dispFile.readlines()
dispFile.close()

displacement = [float(i.strip()) for i in displacement]

a = []
b = []
c = []
d = []
e = []

for displacementval in displacement:
   if displacementval < 2:
        a.append(displacementval)
   elif displacementval < 2.1:
        b.append(displacementval)
   # ... the rest is similar, so omitted
print a
print b

I would suggest reading the official Python tutorial, so you get an idea of Python syntax first.

azalea
  • 11,402
  • 3
  • 35
  • 46
2

When you get the hang of the above beginner friendly solutions, consider taking a look at bisect.

You can solve your problem by doing a little semantic modification of the linked example.

from bisect import bisect

def grade(score, breakpoints=[2, 2.1, 2.25, 2.5], marks='abcde'):
        i = bisect(breakpoints, score)
        return marks[i]

a,b,c,d,e = [], [], [] ,[], []
lists = [a,b,c,d,e]
marks='abcde'

r = map(lambda x: x / 10.0, range(0, 501, 1))

for item in [(grade(score),score) for score in r ]:
    l = marks.index(item[0])
    lists[l].append(item[1])

grade() , for a given number will ask, at what index would it go if it were to be inserted in breakpoints? And it will return marks[index]. For example if you gave it a score of 1, it would calculate that 1 belongs in index 0 of breakpoints before 2, so it will return marks[0]=a.

the print statement will give you a list of tuples containing (letter mark, value that mark is assigned to).

As I said this is more advanced and you should try to get to understand it after you grasped basic concepts, but it's worth taking a look at to bend your mind a little.

themistoklik
  • 880
  • 1
  • 8
  • 19
  • Great solution! But I would suggest using the original data in the question as an example, so `numpy` is not needed (since it does not come with Python by default). – azalea Dec 08 '16 at 20:01
  • Thank you, I needed a quick way to demonstrate float ranges, do you know if STL supports that by default? – themistoklik Dec 08 '16 at 20:02
  • 1
    There are multiple ways as discussed in this thread: http://stackoverflow.com/a/7267287/1292238 – azalea Dec 08 '16 at 20:07
  • @azalea thanks, it was simple enough, edited with list dispatching – themistoklik Dec 08 '16 at 20:15
0
import os
import numpy
os.chdir('/Users/DevEnv')

dispFile = open('output1.txt')
displacement = dispFile.readlines()
dispFile.close()

displacement = [float(i.strip()) for i in displacement]
a = []
b = []
c = []
d = []
e = []

for i in displacement:
    if i <2:
        a.append(i)
    elif i < 2.1:
        b.append(i)
    elif i < 2.25:
        c.append(i)
    elif i< 2.5:
        d.append(i)
    else:
        e.append(i)

Don't forget to instantiate the lists, and the line if i<2 displacementval()=a(): doesn't mean anything.

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
0

There's a couple of issues here, but I'll try my best to walk you through them. First off, you said you wanted 5 variables: a, b, c, d, e, and that each should hold a list of values. To do this we must first declare each as a list, which, in Python is just a collection of values. This looks like this:

a = []
b = []
c = []
d = []
e = []

Next during our for loop, we need to compare the values and sort them accordingly, like this:

for i in range(0, 50):
    displacementval = displacement[i]
    if displacementval < 2:
        a.append(displacementval)
    elif displacementval < 2.1:
        b.append(displacementval)
    elif displacementval < 2.25:
        c.append(displacementval)
    elif displacementval < 2.5:
        d.append(displacementval)
        e.append(displacementval)

A little explanation: when we use a_list.append(a_value) we are adding that value on to the end of the list. Also, our if statement just checks if something is true, and then moves onto the next elif. So if a value is not < 2, it will go to the next and check if it's less than 2.1, if it is it must be greater than or equal to 2 and less than 2.1, and so on.

Hopefully this helps!

Adam B
  • 1
  • 1
0

Alternatively, you could save all the categories in one dictionary of lists instead of having a separate variable for each category. Here is the code.

from collections import defaultdict
def get_category(i):
    if i < 2:
        return'a'
    elif i < 2.1:
        return 'b'
    elif i < 2.25:
        return 'c'
    elif i < 3:
        return 'd'

displ_categories = defaultdict(list)
for i in displacement:
    category = get_category(i)
    displ_categories[category].append(i)

The resulting dictionary is of the form:

{'a': [0.42, 1.01, 0.118, 0.807, 0.225, 1.307, 1.151, 0.824],
 'd': [2.716, 2.255]}
Sayyor Y
  • 1,130
  • 2
  • 14
  • 27