无法遍历列表并提取数据

2024-10-03 04:36:48 发布

您现在位置: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']]

Tags: the数据number列表that数字requirementsprint
1条回答
网友
1楼 · 发布于 2024-10-03 04:36:48
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

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

相关问题 更多 >