【问题标题】:Python tuple access issue?Python元组访问问题?
【发布时间】:2015-12-12 00:41:00
【问题描述】:

我正在使用 python pyparsing 库,其输出似乎是元组。但是,当尝试作为元组访问时,我得到了意想不到的结果。

>>> from pyparsing import *
>>> aaa = (Literal('xxx') + SkipTo(':')  + Literal(':')('::') + Word(nums)('eee')).parseString('xxx : 123')

>>> aaa
(['xxx', '', ':', '123'], {'eee': [('123', 3)], '::': [(':', 2)]})

奇怪的是:

>>> aaa[0]
'xxx'
>>> aaa[1]
''

我希望aaa[0] 成为列表:

['xxx', '', ':', '123']

和 aaa[1] - 字典:

{'eee': [('123', 3)], '::': [(':', 2)]}

为什么我得到了意想不到的结果?这里发生了什么?谢谢。

【问题讨论】:

  • 你输入 aaa 了吗?类型(aaa)
  • >>> type(aaa) >>> dir(aaa) ['::', 'class', 'delattr', 'doc', 'format', 'get', 'getattribute ', 'hash', 'init', 'new', 'reduce', ' reduce_ex'、'repr'、'self'、'self_class'、'setattr' , 'sizeof', 'str', 'subclasshook', 'thisclass', 'eee'] > >>
  • 查看类似问题的答案:stackoverflow.com/questions/7045757/… ParseResults 对象可以被视为列表、字典或对象。或者您可以使用asList()asDict() 转换它们。但首先尝试这些访问:aaa[0]aaa['eee']aaa.eee。我有点困惑,您在一些未出现在列表中的命名结果中有值,以及为什么有一个名为“::”的命名元素。但这些与这个问题无关。如果你打印出aaa.dump(),你会看到更好的细节。

标签: python list dictionary tuples pyparsing


【解决方案1】:

Python 有一些强大的内省能力。确定什么是问它

>>>type(aaa)
   <class 'pyparsing.ParseResults'>

你能用它做什么,方法和属性

>>>dir(aaa)
   ['::', '__class__', '__delattr__', '__doc__', '__format__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__self_class__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__thisclass__', 'eee']

我看到它有一个 get 方法所以

for each in aaa:
    type(each), each, len(each)

<type 'str'>

for each in aaa:
     type(each), each, len(each)



(<type 'str'>, 'xxx', 3)
(<type 'str'>, '', 0)
(<type 'str'>, ':', 1)
(<type 'str'>, '123', 3)

现在是时候阅读文档了

我会注意到您使用 pyparsing 方法创建了 xxx 和其他这些东西,因此您可以询问它们是什么类型(字面量)并了解它们的内部魔法目录(字面量)有时答案不是很有帮助,但是通常你不会因为问而破坏任何东西。

归根结底,aaa 似乎不是一个元组,我注意到它有一些方法与元组的方法相同,但它没有一个元组的所有方法。

【讨论】:

  • 谢谢,无论如何我都可以得到aaa中的所有信息。就像可能转换为json?我迫切需要所有这些:在元组中具有位置的键/值?再次感谢。
  • 类文档可以在pythonhosted.org/pyparsing在线找到,ParseResults上的文档可以在pythonhosted.org/pyparsing/pyparsing.ParseResults-class.html找到
  • Pyparsing 类也用文档字符串进行了很好的注释,可以使用 python 的 'help' 命令访问,如 'help(Literal)' 或 'help(Literal.parseString)'。这将为您提供除 dir 输出之外的实际文档。
猜你喜欢
  • 1970-01-01
  • 2019-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-06
相关资源
最近更新 更多