é£åï¼Listï¼æ¯å¨pythonä¸å¸¸è¦çè³æåæ ï¼æ¯ç±ä¸æ¬èå è¦èµ·ä¾çä¸åæå¤åè³æï¼ä¸ä¸éå®çæ ¼å¼ï¼é£åï¼Listï¼å §çæ¯åè³æï¼ä»¥ã,ã符èé²è¡åå²ï¼é£å ï¼Listï¼ çèµ·å§ç·¨èçº0ï¼ä¸ä¸åç·¨èçº1ï¼ä»¥æ¤é¡æ¨â¦ãä½ å¯è½æå¾å¥½å¥ï¼ä¸åè®æ¸è£ä¸åè³æ就好äºï¼çºä½ä¸åè®æ¸å §è¦è£é£éº¼å¤è³æï¼èä¾ä¾èªªï¼æ¨è¯å®ææ¬é家ï¼æ¬å®¶æç®±åï¼è®æ¸ï¼æ¯ä½ ç好夥伴ï¼æææå ·ç¨åï¼è³æï¼æ¨ææ¸é¡å¨åä¸åç®±åï¼è®æ¸ï¼ï¼ææçæ¸ç±ï¼è³æï¼ææ¸é¡å¨å¦ä¸åç®±åï¼è®æ¸ï¼ï¼æ¨æé樣åçç®çæ¯ä»éº¼ï¼è¯å®æ¯å çºæ¬å°æ°çä½ææï¼å¯ä»¥å¿«éå°æ¾å°æ±è¥¿ï¼ä»¥æ¹ä¾¿ä¹å¾çå®ä½å§ï¼éä¹æ¯é£åï¼Listï¼éåè®æ¸è¢«åµé åºä¾çç®çã
å¦æä¸ç¥éarrayæ¯ä»éº¼ï¼å¯ä»¥è·³ééä¸æ®µï½
è¥æ¨æå¸éJavaï¼å¯è½æå¾å¥½å¥arrayålistçå·®å¥æ¯ä»éº¼ï¼æ大çå·®å¥å°±æ¯arrayå §çæ¯åè³æåæ é½ä¸æ¨£ï¼èliståå¯ä»¥ä¸åè³æï¼å æ¤å¨è¨æ¶é«çå®æä¸ï¼arrayæè¼ææçä¸é»ãliståç¾çå½¢å¼å¦ä¸æ示ï¼
# é£åä¸çåæ
ä¸éå¶
boxname1 = [1,2,3,4,5]
boxname2 = ['ä½ ', '好', 'æ', 'æ¯', 'é£å']
boxname3 = [[1,2,3],4,5]
boxname4 = [1,
'é½å¯ä»¥æ¾',
[
['A','B'],
[2,3]
]
]
åè³æçæ¹å¼å¾ç°¡å®ï¼åªéè¦å¨è©²è®æ¸å¾æ¹ï¼ä¸æ¨£ä½¿ç¨ä¸æ¬èå è¦æ ¾æåè³æçç·¨èï¼å³å¯åå¾è©²è³æã
>>> boxname2 = ['ä½ ', '好', 'æ', 'æ¯', 'é£å']
>>> boxname2[2]
'æ'
>>> boxname2[4]
'é£å'
>>> boxname2[5] #溢ä½ï¼è¶
åºé£åç¯åäº
IndexError: list index out of range
ã溢ä½ãçæææ¯ï¼è¶ åºé£åçç¯åï¼å¦ä¸èä¾aè®æ¸åªæ5çè³æï¼æå¾ä¸çè³æçç·¨èçº4ï¼å æ¤è¼¸å ¥a[5]è¦æ±ååºç·¨è5çå §å®¹ï¼é»è ¦å°±æå復ãIndexError: list index out of rangeãï¼ä»£è¡¨è¦æ±çç·¨èè¶ åºäºé£åã
>>> a = ['ä½ ', '好', 'æ', 'æ¯', 'é£å']
>>> a[5] #溢ä½ï¼è¶
åºé£åç¯åäº
IndexError: list index out of range
å©ç¨appendæ¹æ³ï¼å¯ä»¥å¨é£åçå¾æ¹æå ¥è³æã
>>> a = [1, 2, 3, 4, 5]
>>> a.append(6)
>>> print(a)
[1, 2, 3, 4, 5, 6]
sortå¯ä»¥å°é£åå §çè³æé²è¡æåºã
>>> a = [9, 4, 5, 3]
>>> a.sort()
>>> print(a)
[3, 4, 5, 9]
åªé¤é£åå §å®¹æå¤ä¸æ¹å¼ï¼ç¬¬ä¸ç¨®æ¯delæ¹æ³ï¼åªè¦å¨delå¾è¼¸å ¥æ³åªé¤çé£åç·¨èå³å¯ãç±ä»¥ä¸ç¯ä¾å¯ç¥ï¼è¼¸å ¥ãdel a[0]ãå¾ï¼é¤äºè³æéå°åªé¤å¤ï¼æ´åè³æçç·¨èæãé 延ãï¼å æ¤è¥éè¤å·è¡ãdel a[0]ãï¼æçµä¸å®æå°æ´åé£åçè³æåªå å ã
>>> a = [1, 2, 3, 4, 5, 6, 7]
>>> del a[0]
>>> print(a)
[2, 3, 4, 5, 6, 7]
>>> del a[0] # è³ææé 延ï¼ä¸ç´å·è¡æä¸ç´ç æ第ä¸åè³æ
>>> print(a)
[3, 4, 5, 6, 7]
removeæ¹æ³æ¯æå®åªé¤è³æã以ä¸ç¯ä¾ä¸è¼¸å ¥4ï¼éå4並ä¸æ¯ç·¨èï¼èæ¯æå®è³ææ¯ã4ãå°±é²è¡åªé¤ï¼ä½ä¸¦ä¸æ¯æ´åé£åä¸ç4é½åªé¤ï¼åªåªé¤ã第ä¸åæ¾å°çãã
>>> a = [1, 2, 3, 4, 5, 6, 7]
>>> a.remove(4)
>>> print(a)
[1, 2, 3, 5, 6, 7]
>>> a = [1, 2, 3, 4, 5, 4]
>>> a.remove(4)
>>> print(a)
[1, 2, 3, 5, 4]
popæ¯æå®åªé¤ç·¨èï¼è¥æ²æè¼¸å ¥ç話ï¼ååªé¤é£åæå¾ä¸åè³æã
>>> a = [1, 2, 3, 4, 5, 6, 7]
>>> a.pop(2) # ææå®ç·¨è2ï¼é£å°±åªé¤ç·¨è2ï¼åªé¤ææé¡¯ç¤ºçµ¦ä½ çåªé¤äºç麼è³æ
3
>>> print(a)
[1, 2, 4, 5, 6, 7]
>>> b = [1, 2, 3, 4, 5, 6, 7]
>>> b.pop() # æ²ææå®ä»»ä½ç·¨èï¼ååªé¤æå¾ä¸å
7
>>> print(b)
[1, 2, 3, 4, 5, 6]
作者:楊超霆 行銷搬進大程式 創辦人