Python — list

2022/05/08閱讀時間約 7 分鐘
— extend() append() insert()
在 Python 中 List 是常常會用到的,其中 List 的一個功能是 extend
使用方法如下:
  • 使用 String 型別
List = list(['value'])
print(List)
List.extend('string')
print(List)
結果:
['value']
['value', 's', 't', 'r', 'i', 'n', 'g']
extend將會分割每個字元放入
  • 使用 List 型別
List = list(['value'])
print(List)
List.extend(['hello', 'world'])
print(List)
結果:
['value']
['value', 'hello', 'world']
extend將會把每個陣列內容放入
  • 使用 Tuple 型別
List = list(['value'])
print(List)
List.extend(('hello', 'world', 'tuple'))
print(List)
結果:
['value']
['value', 'hello', 'world', 'tuple']
結果將會和List一樣
  • 使用 Dict 型別
List = list(['value'])
print(List)
List.extend({'hello':'world', 'dict':'tuple'})
print(List)
結果:
['value']
['value', 'hello', 'dict']
extend將只會把key值傳入而已
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
接下來是append
List = list()
print(List)List.append('list')
print(List)List.append(1)
print(List)List.append({'hello':'world'})
print(List)List.append(('this', 'is', 'tuple'))
print(List)List.append(['this', 'is', 'list'])
print(List)
結果
[]
['list']
['list', 1]
['list', 1, {'hello': 'world'}]
['list', 1, {'hello': 'world'}, ('this', 'is', 'tuple')]
['list', 1, {'hello': 'world'}, ('this', 'is', 'tuple'), ['this', 'is', 'list']]
**不管什麼型別資料只會放入最後,且一次只能傳一個參數
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
最後就是insert
  • 使用 IntString 型別
List = list(['value', 'hello', 'world'])
print(List)
List.insert(1, 22)
print(List)
List.insert(1, 'insert')
print(List)
結果
['value', 'hello', 'world']
['value', 22, 'hello', 'world']
['value', 'insert', 22, 'hello', 'world']
新加入的資料內容就被依序插入至第一個陣列內容
  • 使用 List 和 Tuple 型別
List = list(['value', 'hello', 'world'])
print(List)
List.insert(1, ['insert', 'list'])
print(List)
List.insert(1, ('insert', 'tuple'))
print(List)
結果
['value', 'hello', 'world']
['value', ['insert', 'list'], 'hello', 'world']
['value', ('insert', 'tuple'), ['insert', 'list'], 'hello', 'world']
  • 使用 Dict 型別
List = list(['value', 'hello', 'world'])
print(List)
List.insert(1, {'insert':1, 'dict':2})
print(List)
結果
['value', 'hello', 'world']
['value', {'insert': 1, 'dict': 2}, 'hello', 'world']
**insert 不管什麼資料皆可原封不動插入至陣列
為什麼會看到廣告
John
John
留言0
查看全部
發表第一個留言支持創作者!