Open hug2wisdom opened 5 years ago
想要在循环中修改 list 中的 items 时,需要在 for 语句中使用 list 的切片,即 list[:] ,原因是,如果直接用 for item in list[] 的话,会造成无限循环。
If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you first make a copy. Iterating over a sequence does not implicitly make a copy. The slice notation makes this especially convenient.
You might have noticed that methods like insert
, remov
e or sort
that only modify the list have no return value printed – they return the default None. This is a design principle for all mutable data structures in Python.
Note that in Python, unlike C, assignment cannot occur inside expressions. C programmers may grumble about this, but it avoids a common class of problems encountered in C programs: typing = in an expression when == was intended.
需要注意的是Python与C不同,在表达式内部不能赋值。C 程序员经常对此抱怨,不过它避免了一类在 C 程序中司空见惯的错误:想要在解析式中使 == 时误用了 = 操作符。
a = b + c
左边 a 表示变量 variable , 右边 b + c 表示表达式, 而表达式里不能赋值,即不能出现:a = b == 1 + c == 2
def reverseWords(input):
# 通过空格将字符串分隔符,把各个单词分隔为列表
inputWords = input.split(" ")
# 翻转字符串
# 假设列表 list = [1,2,3,4],
# list[0]=1, list[1]=2 ,而 -1 表示最后一个元素 list[-1]=4 ( 与 list[3]=4 一样)
# inputWords[-1::-1] 有三个参数
# 第一个参数 -1 表示最后一个元素
# 第二个参数为空,表示移动到列表末尾
# 第三个参数为步长,-1 表示逆向
inputWords=inputWords[-1::-1]
# 重新组合字符串
output = ' '.join(inputWords)
return output
if __name__ == "__main__":
input = 'I like runoob'
rw = reverseWords(input)
print(rw)
# result
runoob like I
list.index(x) | 返回列表中第一个值为 x 的元素的索引。如果没有匹配的元素就会返回一个错误。 |
---|
list.copy() | 返回列表的浅复制,等于a[:] |
---|
shallow copy(浅复制)
clear the list: