【问题标题】:For Loop to read but need to skip specific range values循环读取但需要跳过特定范围值
【发布时间】:2019-04-15 00:49:36
【问题描述】:

我正在尝试用 Python 编写一个程序来读取文本文件。文本文件如下所示:

<br>12345,Ballpeen Hammer,25,18.75</br>

56789,Phillips Screwdriver,120,10.95

24680,Claw Hammer,35,15.98

13579,Box Wrench,48,20.35

28967,Hex Wrench,70,19.98

我写的代码:

import inventoryitem2
FILENAME = ('item_numbers.txt')
# Open the text file.
infile = open(FILENAME, 'r')


def main():

    current_numbers = current_list()
    #print(current_numbers)

    # Print using the class. 
    #items = inventoryitem2.InventoryItem2(item_number)
    #print(items)

# Function for getting item numbers.
def current_list():

    # Empty list.
    item_number = []

    for line in infile:
        item_numbers = line.split(',')[0]
        item_number.append(item_numbers)

    for numbers in item_number:
        print(numbers)


main()

它读取文件并构建一个我想要的列表,但我只想要以 20000 到 79999 范围内的值开头的行。我编写了一个名为 'inventoryitem2' 的类,它传递数字并使用定义 str

我在哪里设置这个条件以及如何设置?

【问题讨论】:

标签: python for-loop readfile


【解决方案1】:

Python 原生支持 Comma Separated Value (CSV) files,我建议您使用它(您的数据至少看起来像 CSV)。

你可以使用类似下面的东西:

import csv

lower_limit = 20000
upper_limit = 79999
items = []

with open('item_numbers.csv', newline='') as csvfile:
  item_reader = csv.reader(csvfile)
  # Loop through the rows
  for row in item_reader:
    # CSV automatically splits the row into a list of strings on the `,`
    # so we just need to convert the first value - `row[0]` to an int 
    # and compare it to your limits
    if (int(row[0]) >= lower_limit) and (int(row[0]) <= upper_limit):
      # add the list of strings `["12345", "Ballpeen Hammer", "25", "18.75"]`
      # to the items list
      items.append(row)

print(items)

【讨论】:

  • 很好,非常感谢。我只是在学习 Python(到目前为止非常喜欢它),并从我上过的一门课程中收到了一个项目,但几乎没有通过。虽然下课了,但我还是想了解OOP。我会试试你建议的答案。
  • 酷,这将让我开始我想要完成的事情。感谢您向我展示如何在 for 循环中放置条件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多