2

Well, I can easily use this code without errors on Python:

>>>> a = range(5, 10)
>>>> b = range(15, 20)
>>>> a.extend(b)
>>>> a
[5, 6, 7, 8, 9, 15, 16, 17, 18, 19]

I also can use this method, without using b:

>>>> a = range(5, 10)
>>>> a.extend(range(15, 20))
>>>> a
[5, 6, 7, 8, 9, 15, 16, 17, 18, 19]

But I can't figure out why the same thing doesn't happen in this case:

>>>> [5, 6, 7, 8, 9].extend(range(15, 20))
>>>>

Wasn't a supposed to be the same thing as the above list? I only see as difference that I hardcoded the inicial state. I could really understand that the hardcoded list cannot be modified while it's not in a variable or something but...

>>>> [5, 6, 7, 8, 9][2]
7

This surprises me. What is even more strange:

>>>> [5, 6, 7, 8, 7].count(7)
2
>>>> [5, 6, 7, 8, 7].index(8)
3

Why can some list methods work on a hardcoded/not-in-a-variable list, while others can?

I'm not really into using this, that's more for personal knowledge and understanding of the language than usefulness.

4

1 回答 1

6
  1. extend不返回值。因此,打印a.extend(b)将是None. 因此,如果您拥有a = [5, 6, 7, 8, 9].extend(range(15, 20))并打印a,它将显示None. 一种解决方法是连接列表a = [5, 6, 7, 8, 9] + range(15, 20)

  2. [5, 6, 7, 8, 9][2]- 一切都是应该的,因为它从 0 开始计数元素。它不是在修改列表,它只是从列表中返回某个元素。

  3. [5, 6, 7, 8, 7].count(7)[5, 6, 7, 8, 7].index(8)显示预期的输出。第一个是 7 在列表中出现的次数,第二个是数字 8 的索引(同样,从 0 开始计数)。

因此,总而言之,硬编码列表的使用在您生成的所有示例中都符合预期。

于 2013-08-27T04:39:04.497 回答