【问题标题】:How to parse words from strings in a list, when the list is in a tuple?当列表在元组中时,如何从列表中的字符串中解析单词?
【发布时间】:2020-10-20 15:53:59
【问题描述】:

我正在倒退我当前的任务。我的数据格式为:

qn1 = (["123 + 12", "234 + 23"], True)

我需要阅读方程式字符串并解析各个单词。我的问题是我无法拆分列表中的字符串,因为列表在一个元组中。

我想要的输出是:

到目前为止,我的搜索将我带到了;

This other s/flow question; but that is not what am looking for

请不要为我解决整个问题。 我喜欢挑战,(这是我freecodecamp 考试的一部分)

我只需要一些指针来解决问题。

我发现我的问题与How can I split and parse a string in Python? 的问题不同,因为我不只是拆分一个元组,而是在一个元组内拆分一个列表,(在空格内进一步拆分字符串,以便我可以选择里面的数字和“+”号来排列它们。)

【问题讨论】:

  • 查看如何解包元组和列表,然后您可以访问各个元素并拆分它们。
  • qn1[0] 为您提供元组的第一个元素。 qn1[0][0].split()给你['123', '+', '12'],希望对你有帮助。
  • 这能回答你的问题吗? How can I split and parse a string in Python?
  • 嘿@Mark,我仍然有问题,因为print(qn1[0][0][0]) 给了我1。我怎样才能得到123这是我想要的?
  • @ChristopherPeisert 我已经尝试过了,但我无法从那个特定的问题中得到答案。谢谢

标签: python


【解决方案1】:

首先从元组中获取数据。

>>> qn1 = (["123 + 12", "234 + 23"], True)
>>> equations, flag = qn1
>>> equations
['123 + 12', '234 + 23']

或者您可以在元组中使用索引:

>>> qn1 = (["123 + 12", "234 + 23"], True)
>>> equations = qn1[0]
>>> equations
['123 + 12', '234 + 23']

接下来,将方程分成几部分:

>>> for equation in equations:
...     tokens = equation.split()
...     print(tokens)
... 
['123', '+', '12']
['234', '+', '23']

要开始解析数学表达式,请参阅:
Evaluating a mathematical expression in a string

有关格式化输出的想法,请参阅:
Create nice column output in python

【讨论】:

    【解决方案2】:

    您需要将字符串拆分为列表,以便将它们放入打印语句中

    希望这会给你带来一些挑战:^)

    qn1 = (["123 + 12", "234 + 23"], True)
    
    eq1 = []
    eq2 = []
    
    #try to get a list of the parts of that equation. E.g ["567", "+", "56"]
    
    print(f"{eq1[0]}     {eq2[0]}")
    print(f"{eq1[1]} {eq1[2]}   {eq2[1]} {eq2[2]}")
    print(f"====    ====")
    

    【讨论】:

    • 是的,它有点挑战性,也很棒。谢谢你,我一直在努力,还没有完成,但它不再是一堵砖墙。所以谢谢
    猜你喜欢
    • 2011-03-31
    • 1970-01-01
    • 2010-12-21
    • 2013-01-24
    • 1970-01-01
    • 2023-04-03
    • 2020-07-21
    • 2011-02-02
    • 2021-10-12
    相关资源
    最近更新 更多