首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Python中满足条件时如何将文本文件中的数字与字符串相加

在Python中满足条件时如何将文本文件中的数字与字符串相加
EN

Stack Overflow用户
提问于 2022-02-20 14:21:23
回答 1查看 291关注 0票数 0

我正在做一个库存系统,要求我打印特定物品的分销清单。如果某一商品已分发到同一家商店超过一次,它需要将数量相加在一起。

我不允许使用字典和熊猫。只能使用列表

项需要使用代码进行搜索

交易文本文件:

S001,T01,T恤,4

S001,T01,T恤,7

S002,T02,鞋,9岁

S003,T02,鞋子,11岁

第一个是商店代码,第二个是商品代码,然后是商品名称和分配数量。

这是我的密码

代码语言:javascript
复制
x=open("transactions.txt","r")
numbers = []
total = 0
searchInput=input("Enter item code to search: ")
for line in x:
      lines = line.strip()
      s = lines.split(",")
      numbers.append(s)
      if not searchInput.lower() in lines.lower():
            continue
      column = -1
      record = len(numbers)
      for v in range(record):
            if searchInput == s[1]:
                  column = v
      if ((numbers[column][0] == numbers[column][0]) and (numbers[column][1] == numbers[column][1])):
            num = int(numbers[column][-1])
            total += num
if column >=0:
      a=numbers[column][0]+","+numbers[column][1]+","+numbers[column][2]+","+str(total)
      print(a)

当我输入T01 for searchInput时,它可以用最新的总数正确地打印。但是当我在T02中输入时,它会总结我的总数,即使是商店代码也是不同的。它应该打印2行T02,而不加起来。

当我输入T02 for searchInput时,输出应该如下所示

S002,T02,鞋,9岁

S003,T02,鞋子,11岁

EN

回答 1

Stack Overflow用户

发布于 2022-02-20 15:21:01

我已经尝试过猜测您的具体用例,所以我的示例可能有点错误。首先,让我介绍一下您的一些代码,并给出我的一些评论:

代码语言:javascript
复制
numbers = []
total = 0
x = open("transactions.txt","r")

for line in x:

    print(line)

    lines = line.strip()
    s = lines.split(",")

    numbers.append(s)
    print(numbers)

    if not searchInput.lower() in lines.lower():
        # keep only the lines which have a match with the search input
        continue

    column = -1
    record = len(numbers)
    print(f'len(numbers): {len(numbers)}')

    for v in range(record):
        # 
        if searchInput == s[2]:
            # s is the current line, 2 denotes the 3rd entry e.g. the item
            # column will be overwritten by v as long as searchInput matches s[2] exactly
            # column will therefore be equal to len(numbers)-1
            column = v
            print(f'column: {column}')

    if ((numbers[column][0] == numbers[column][0]) and (numbers[column][1] == numbers[column][1])):
        # if one item equals itself, and another item equals itself, then:
        # num is the integer of last value in the column record
        num = int(numbers[column][-1])
        total += num

请注意输出是如何不清楚的。使用Python的关键特性之一是保持代码清晰易读,因此当其他人(或您未来的自我)返回到此代码时,您可以从您离开的地方开始。

基于您所告诉的,我尝试以以下方式重新编写您的代码。请特别注意变量的命名。请注意,此示例是一个非常基本的示例,如果您处理输入数据,您可能需要在其中包装一些try-除了语句和错误处理。当然,您也可以决定切换到其他库,比如csv,因为您已经有了一个逗号分隔的值,甚至可以在其中进行熊猫,为这些列命名以便于阅读,甚至添加日期时列,这样就可以过滤日期。不管怎么说,我认为你想达到的目标是:

代码语言:javascript
复制
searchInput = input("Enter item code to search: ").lower()

records = list()
transactions = open("transactions.txt","r")

for record in transactions:
    # cleaning the record by stripping leading and trailing spaces, lowering cases and splitting on the commas
    clean_record = record.strip().lower().split(',')

    if any([searchInput in x for x in clean_record]):
        # keep only the lines which have a match with the search input
        records.append(clean_record)

total = dict()
for record in records:
    # now that we have all the records we want
    # we will retrieve the relevant information
    # we want a the sum of the values, printed for each store
    if record[0] not in total.keys():
        total[record[0]] = int(record[-1])
    else:
        total[record[0]] += int(record[-1])

for shop, tot in total.items():
    print(f'Shop: {shop} - Total: {tot}')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71195336

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档