根据Python中的值对数字列表进行分类 [英] Classify a list of numbers based on their values in Python
问题描述
我正在尝试在python中编写一个循环,该循环读取50个数字的文本文件,并对数字进行排序,然后根据其值将它们分配给不同的变量.我希望变量A包含小于2的值,变量B包含2到2.1的值,变量c包含2.1到2.25的值,变量d包含2.25到2.5的值,变量e包含从2到2.5的值. 2.25至2.5.
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():
但是,当我尝试运行此命令时,出现无效的语法错误.我是python和程序设计的新手,将不胜感激!
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!
推荐答案
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
我建议您阅读官方的 Python教程,这样您就可以首先是Python语法的想法.
I would suggest reading the official Python tutorial, so you get an idea of Python syntax first.
这篇关于根据Python中的值对数字列表进行分类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!