1. 程式人生 > >Python練習11----list賦值給變數

Python練習11----list賦值給變數

如何將list中的值快速賦值給變數,如下:
a, b, c, d = list1
這種方式只有當左邊的運算元個數和list1長度相同時,才可以這麼做,不然不報錯.
假設我們有一個list物件List,它的長度足夠長,想把它從下標i開始的k個元素賦給k個元素,可以這麼做:
v1, v2, v3, …, vk = List[i : i + k] #預設i=0, k=len(List)
a, b, c, d = list1相當於:
a, b, c, d = list1[0 : 4]

練習程式碼

#Hello World program in Python
# -*- coding: utf8 -*-
lists=[] lists.append(3) lists.append(4) a,b=lists print("a,b,sum:",a,b,a+b) c=0 for i in lists: c=c+i print("sum:",c)

這裡寫圖片描述