无法遍历列表并提取数据

时间:2017-10-24 01:50:22

标签: python

我的python脚本遇到了一些麻烦。我希望能够从文本文件中获取值,将它们放在列表中,然后提取满足条件且不符合条件的数字。当我从文本文件中分割并提取数据时,我的问题就出现了。我能够遍历列表,但是当涉及到组织数据时,我没有看到正确的数据。我希望能够在列表中放置大于y的数字并且小于Y在另一个列表中。我传递的文本文件包含浮动此文件有8行。

def openTextFileAndRead(x):
    > x = sys.argv[1]
    organized_high = []
    organized_low = []
    index = 0
    y = float(109.0)
    with open(x, 'r') as f:
        unorganizedFloatList = []
        for lines in f:
            unorganizedFloatList.append(lines.rstrip().split(","))
            lenghOfList = len(unorganizedFloatList)
        for numbers in unorganizedFloatList:
            index += 1
            if numbers >= y:
                print ("printing the numbers that meet the high number requirements\n")
                organized_high.append(numbers)
                print organized_high
                if index == lenghOfList:
                    break
            else:
                print('printing numbers that didnt meet the high requirements')
                organized_low.append(numbers)
                print organized_low

输出

[['12.3']]
printing the numbers that meet the high number requirements

[['12.3'], ['124.5']]
printing the numbers that meet the high number requirements

[['12.3'], ['124.5'], ['54.3']]
printing the numbers that meet the high number requirements

[['12.3'], ['124.5'], ['54.3'], ['53.2']]
printing the numbers that meet the high number requirements

[['12.3'], ['124.5'], ['54.3'], ['53.2'], ['3.2']]
printing the numbers that meet the high number requirements

[['12.3'], ['124.5'], ['54.3'], ['53.2'], ['3.2'], ['8.0']]

1 个答案:

答案 0 :(得分:1)

for lines in f:
    unorganizedFloatList.append(lines.rstrip().split(","))
    lenghOfList = len(unorganizedFloatList)

在计算每次迭代中列表的长度时,没有任何意义。您可能希望在填写列表后计算长度:

for lines in f:
    unorganizedFloatList.append(lines.rstrip().split(","))
lenghOfList = len(unorganizedFloatList)

另外,关于这一行:

unorganizedFloatList.append(lines.rstrip().split(","))

Split返回一个列表。因此,您要将列表附加到列表中,这就是您的打印显示列表列表的原因。对于我看到你的分裂总是返回1个值,所以要有一个你可能想要的平面列表:

unorganizedFloatList.append(lines.rstrip().split(",")[0])

通过这种方式,您始终可以获得拆分的第一个元素,并将其附加到列表中,这将为您提供一个平面的字符串列表。这就是为什么你说你没有看到"正确的数据"?

你不需要在这里跟踪索引:

for numbers in unorganizedFloatList:
        index += 1
        if numbers >= y:
            print ("printing the numbers that meet the high number requirements\n")
            organized_high.append(numbers)
            print organized_high
            if index == lenghOfList:
                break

对于cicle,这将在您的索引等于列表的长度之前退出。您已经在使用for cicle迭代所有元素,您不需要索引。