1
ca1n 2015-06-23 10:32:54 +08:00
>>> a = list()
>>> a[:10] = [x for x in range(100)] >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99] |
2
aheadlead 2015-06-23 10:39:07 +08:00
>>> a = list()
>>> a = [chr(_) for _ in range(ord('a'), ord('z')+1)] >>> a ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] >>> a[:10] = [x for x in range(100)] >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] |
4
weyou 2015-06-23 13:51:10 +08:00
```
s[i:j] = t slice of s from i to j is replaced by the contents of the iterable t ``` 其实@aheadlead 的代码已经说明一切了。 a[:10] = [x for x in range(100)] 这个赋值是用后面的100个值代替a前面10个元素的位置。 所以你的第二问“后面的 90 个元素怎么处理的”也就没有意义了。 另外,话说干嘛用列表解析,直接用list就可以了,效果一样: a[:10] = list(range(100)) |
5
weyou 2015-06-23 13:53:22 +08:00
上面的那个例子更正一下,其实用:
a[:10] = range(100) 就行了,效果也是一样 |