在問候你的代碼,我建議這個編輯:
original_list = ['p','q','r','x','t','l','z','y','x','a','b']
def make_new_list(n, old_list):
new_list = old_list[:n]
return new_list
print (make_new_list(2, original_list))
您可以切片一個列表,像這樣:
original_list = ['p','q','r','x','t','l','z','y','x','a','b']
new_list = original_list[:2]
打印:
['p', 'q']
或從端:
original_list = ['p','q','r','x','t','l','z','y','x','a','b']
new_list = original_list[2:]
打印:
['r', 'x', 't', 'l', 'z', 'y', 'x', 'a', 'b']
或扭轉的列表:
original_list = ['p','q','r','x','t','l','z','y','x','a','b']
new_list = original_list[::-1]
打印:
['b', 'a', 'x', 'y', 'z', 'l', 't', 'x', 'r', 'q', 'p']
或反向切片:
original_list = ['p','q','r','x','t','l','z','y','x','a','b']
new_list = original_list[:-2]
打印:
['p', 'q', 'r', 'x', 't', 'l', 'z', 'y', 'x']
再次逆轉,雖然有點多餘:
original_list = ['p','q','r','x','t','l','z','y','x','a','b']
new_list = original_list[-2:]
打印:
['a', 'b']
或獲得元素不在開始:
個
original_list = ['p','q','r','x','t','l','z','y','x','a','b']
new_list = original_list[2:4]
打印:
['r', 'x']
original_list [:2]? – manvi77
遞增i。要麼'i = i + 1'或'i + = 1' – Himaprasoon
@ manvi77謝謝。請將此作爲答案提交。 –