我需要在Python的切片表示法上有一个很好的解释(引用是一个加号).
对我来说,这种符号需要一点点提升.
它看起来非常强大,但我还没有完全了解它.
我来自以下代码:
# O(n) space
def rotate(self, nums, k):
deque = collections.deque(nums)
k %= len(nums)
for _ in xrange(k):
deque.appendleft(deque.pop())
nums[:] = list(deque) # <- Code in question
Run Code Online (Sandbox Code Playgroud)
nums[:] =那nums =不是做什么的?就此而言,那不做nums[:]什么nums?
from pprint import *
sites = [['a','b','c'],['d','e','f'],[1,2,3]]
pprint(sites)
for site in sites:
sites.remove(site)
pprint(sites)
Run Code Online (Sandbox Code Playgroud)
输出:
[['a', 'b', 'c'], ['d', 'e', 'f'], [1, 2, 3]]
[['d', 'e', 'f']]
Run Code Online (Sandbox Code Playgroud)
为什么不是None,或者是空列表[]?
例如 iftableState是一个元组,我们声明一个变量:
x = tableState[1][:]
Run Code Online (Sandbox Code Playgroud)
那意味着什么[:]?
我刚刚浏览了python docs教程的循环技术章节,我在这里有一个关于这个男孩的问题: [:]
我了解到它需要字符串的开始和结束索引,因此:
text = "This is text"
text[:] # will return the whole text "This is text" and
tex[:4] # will return "This".
Run Code Online (Sandbox Code Playgroud)
但是当我在这里看到这段代码时......
words = ['cat', 'dog', 'cowcowcow']
for w in words[:]: # Loop over a slice copy of the entire list.
if len(w) > 6:
words.insert(0, w)
print words
Run Code Online (Sandbox Code Playgroud)
输出:
['cowcowcow', 'cat', 'dog', 'cowcowcow']
Run Code Online (Sandbox Code Playgroud)
...我不理解for循环中[:]的含义.我会写的
for w in words:
Run Code Online (Sandbox Code Playgroud)
但是当我这样做时,这是一个无休止的循环,为什么呢?