开发者

Appending tuples to lists

What's the proper syntax for adding a recomposed tuple to a list?

For example, if I had two lists:

>>> a = [(1,2,3),(4,5,6)]
>>> b = [(0,0)]

Then I would开发者_如何学C expect the following to work:

>>> b.append((a[0][0],a[0,2]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not tuple

Furthermore, when it informs me that indices must be integers, how come this works?

>>> b.append((7,7))
>>> b
[(0, 0), (7, 7)]


you have try to do this:

(a[0][0],a[0,2])
           ^^^

this is like doing:

(a[0][0],a[(0,2)])

which like the error said : list indices must be integers, not tuple

if i'm not mistaken, i think you wanted to do:

b.append((a[0][0],a[0][2]))


Your problem is this:

b.append((a[0][0],a[0,2]))
                     ^

You try to use the nonexistent tuple index [0, 2] when you mean [0][2]


The indices must be integers. It's just a typo where you have a[0,2] instead of a[0][2]. The [0,2] is an attempt to index by tuple.


a[0,2] is your problem.

It's not complaining about the append, it's telling you that [0,2] cannot be used as an index for the list a.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜