【发布时间】:2011-10-17 03:50:46
【问题描述】:
尝试在 Python 中使用 getattr 和 setattr 函数访问/分配列表中的项目。
不幸的是,似乎无法将列表索引中的位置与列表名称一起传递。
以下是我尝试的一些示例代码:
class Lists (object):
def __init__(self):
self.thelist = [0,0,0]
Ls = Lists()
# trying this only gives 't' as the second argument. Python error results.
# Interesting that you can slice a string to in the getattr/setattr functions
# Here one could access 'thelist' with with [0:7]
print getattr(Ls, 'thelist'[0])
# tried these two as well to no avail.
# No error message ensues but the list isn't altered.
# Instead a new variable is created Ls.'' - printed them out to show they now exist.
setattr(Lists, 'thelist[0]', 3)
setattr(Lists, 'thelist\[0\]', 3)
print Ls.thelist
print getattr(Ls, 'thelist[0]')
print getattr(Ls, 'thelist\[0\]')
另请注意,在 attr 函数的第二个参数中,您不能在此函数中连接字符串和整数。
干杯
【问题讨论】:
-
@BrainStorm 的回答是正确的,但这通常带有“你的做法错误”的味道。你到底想完成什么?
-
这到底是什么……?列表中的项目不是列表的属性,所以这显然行不通。
-
你真正想做什么?
-
@insomniaccanuck 我们知道您在这种情况下要尝试做什么,但是您正在尝试解决一个更大的问题,促使您尝试这些。也许您是trying to parse a hierarchical query string into nested objects/lists 或者您想要一个配置项,它可以让您从配置项中唯一地遍历嵌套对象层次结构,或者您可能正在尝试做其他事情,但是有关更大图景的更多信息将帮助我们指导您解决方案。
-
好的,更多的阅读和思考我认为最好的方法是使用带有嵌套列表的字典。函数 setattr 没有我需要的功能(可能有充分的理由)。我试图做的是建立一个 n 维集合来处理一个排列组。我来自组合学背景;还没有那么多 CS 术语。学习python(和编码)来尝试找工作。谢谢大家