getattr用于Python中的列表索引?

时间:2015-11-21 21:27:05

标签: python getattr

我知道我可以尝试/除了if / else并根据错误或else子句设置默认值,但我只是想知道是否有一个可以像getattr那样做的单行

1 个答案:

答案 0 :(得分:6)

:只是def my_getitem(container, i, default=None): try: return container[i] except IndexError: return default 帮助函数

item = container[i] if i < len(container) else default

糟糕:您可以对条件版本进行单行化

item = (container[i:] + [default])[0]

item, = container[i:i+1] or [default]

item = container[i] if container[i:] else default

item = dict(enumerate(container)).get(i, default)

item = next(iter(container[i:i+1]), default)

丑陋:这些都是黑客,不要使用。

{
"metadata": {
    "generator": "io_three",
    "type": "Geometry",
    "vertices": 8,
    "faces": 6,
    "uvs": 0,
    "normals": 8,
    "version": 3
},
"uvs": [],
"name": "CubeGeometry",
"faces": [33,0,1,2,3,0,1,2,3,33,4,7,6,5,4,5,6,7,33,0,4,5,1,0,4,7,1,33,1,5,6,2,1,7,6,2,33,2,6,7,3,2,6,5,3,33,4,0,3,7,4,0,3,5],
"normals": [0.577349,-0.577349,-0.577349,0.577349,-0.577349,0.577349,-0.577349,-0.577349,0.577349,-0.577349,-0.577349,-0.577349,0.577349,0.577349,-0.577349,-0.577349,0.577349,-0.577349,-0.577349,0.577349,0.577349,0.577349,0.577349,0.577349],
"vertices": [1,-1,-1,1,-1,1,-1,-1,1,-1,-1,-1,1,1,-1,0.999999,1,1,-1,1,1,-1,1,-1]