【问题标题】:Inputlines must be converted to tuples输入行必须转换为元组
【发布时间】:2019-06-20 23:57:32
【问题描述】:

我有一个如下所示的输入文件:

4 * 2 ^ 3 + 4 ^ 1 2 * 1 ^ 2 + 2 ^ 3

并且可能会有更多行。我需要做的是提取* 符号之前的值,所以第一行是4。然后我需要创建一个元组g = [(2,3),(4,1)],因此元组对由+ 分隔,然后对本身由^ 分隔。

my_input = open('input.txt').readlines()
lines = [str(line) for line in 
open('input.txt','r').read().split('\n')]
per_line = str(lines[0]).split('*')
x = int(per_line[0])
terms = str(per_line[1].split('+'))

现在如果我print terms 我得到['2 ^ 3 ', ' 4 ^ 1'],如果我print x 我得到4,那么这似乎有效。但现在我需要以所描述的元组形式获取这些值。如果我在'^' 上再次拆分,我不会得到所需的结果,而是["['2 ", " 3 ', ' 4 ", " 1']"],这是行不通的。我用factors = str(terms.split('^'))尝试过。

我还需要进行一次迭代,以便它适用于所有行,但我可以稍后再做。我首先要确保它仅适用于第一行。

有什么建议吗?

【问题讨论】:

  • If I split again on '^' I don't get the result needed。请出示您的代码。
  • factors = str(terms.split('^'))
  • 你为什么到处使用str

标签: python input readlines


【解决方案1】:

这是一个更好的方法:

import re

x = []
g = []
with open('input.txt') as infile:
    for line in infile:
        nums = re.split(r'[\*\^\+]', line)
        x.append(int(nums[0]))
        g.append((int(nums[1]), int(nums[2])))

print(x) # [4, 2]
print(g) # [(2, 3), (1, 2)]

【讨论】:

  • 很好,从来不知道你可以在一行中拆分多个字符,非常整洁:)
【解决方案2】:

现在如果我print terms 我得到['2 ^ 3 ', ' 4 ^ 1']

然后对于terms 中的每个值(字符串),您必须在 '^' 上进行拆分,然后将每个结果转换为 int 并打包成元组:

g = [tuple(map(int, x.split('^'))) for x in terms]

这是

  1. 获取每个字符串,例如。 '2 ^ 3 '
  2. 将其拆分为列表,例如。 ['2 ', '3 ']
  3. int 函数应用于每个带有map 的列表元素
  4. 制作映射结果的元组

【讨论】:

    【解决方案3】:

    我会首先收集字符串中的所有数字,将它们分配给它们各自的元组,然后将它们分配给一个列表。

    my_input = open('input.txt').readlines()
    lines = [str(line) for line in
    open('input.txt','r').read().split('\n')]
    per_line = str(lines[0]).split('*')
    x = int(per_line[0])
    terms = str(per_line[1].split('+'))
    
    #Start Soln Here ->
    to_parse = terms.replace('^', ',')
    #Tuples to populate final list g
    a = ()
    b = ()
    #To hold int-converted values from file stream
    operands = []
    for i in to_parse:
        if i.isdigit():
            operands.append(int(i))
        #to prevent the inclusion of operators.
        else:
            continue
    #operands list is populated now... Last thing to do is assign them to your tuples!
    a = operands[0], operands[1]
    b = operands[2], operands[3]
    g = [a,b]
    #test output
    print(g)
    

    返回

    [(2, 3), (4, 1)]
    
    Process finished with exit code 0
    

    这有点像话匣子解决方案,但应该可以完成工作

    【讨论】:

      【解决方案4】:

      如果您要解析通用表达式,则可能需要构建解析树:

      from lark import Lark
      
      parser = Lark('''
          ?sum: product
              | sum "+" product       -> add
              | sum "-" product       -> sub
      
          ?product:
              | product "*" exponent  -> mul
              | product "/" exponent  -> div
              | exponent
      
          ?exponent:
              | item "^" exponent     -> exp
              | item
      
          ?item: NUMBER               -> number
              | "-" item              -> neg
              | "(" sum ")"
      
          %import common.NUMBER
          %import common.WS
          %ignore WS''', start='sum')
      
      s = '4 * 2 ^ 3 + 4 ^ 1'
      tree = parser.parse(s)
      print(tree.pretty())
      

      结果:

      add
        mul
          number      4
          exp
            number    2
            number    3
        exp
          number      4
          number      1
      

      【讨论】:

      • 我不熟悉这种类型的解析树。感谢您的洞察力:)
      猜你喜欢
      • 1970-01-01
      • 2014-01-31
      • 2021-04-18
      • 2016-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-14
      相关资源
      最近更新 更多