1. 程式人生 > 其它 >Python-列表-切片(十七)

Python-列表-切片(十七)

#切片:指定列表第一個元素和最後一個元素的索引。
teams=['duoji','zhanglei','xiaoxiao','yuli','tangjie']
print(teams[0:2])
print(teams[2:])
print(teams[-3:])
print('-------------------------------------------------------------------')
#可以在for迴圈中使用切片,對列表中的部分元素進行切片
print('this is our teams :')
for team in teams[:3]:
    print(team.title())

print('-------------------------------------------------------------------')
#可以使用[:]複製列表  將原來的列表複製為一個副本

my_foods = [ 'pizza','falafel','carrot cake']
friend_foods = my_foods[:]

print('My favorite food are:')
print(my_foods)

print("\nMy friend's favorite foods are:")
print(friend_foods)
print('-------------------------------------------------------------------')

my_foods.append('cannoli')
friend_foods.append('ice cream')

print('My favorite food are:')
print(my_foods)

print("\nMy friend's favorite foods are:")
print(friend_foods)
print('-------------------------------------------------------------------')

執行結果

C:\Users\yong.chen.cd\PycharmProjects\pythonProject1\venv\Scripts\python.exe C:/Users/yong.chen.cd/PycharmProjects/pythonProject1/study_python/list_study/list_slice.py
['duoji', 'zhanglei']
['xiaoxiao', 'yuli', 'tangjie']
['xiaoxiao', 'yuli', 'tangjie']
-------------------------------------------------------------------
this is our teams :
Duoji
Zhanglei
Xiaoxiao
-------------------------------------------------------------------
My favorite food are:
['pizza', 'falafel', 'carrot cake']

My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake']
-------------------------------------------------------------------
My favorite food are:
['pizza', 'falafel', 'carrot cake', 'cannoli']

My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'ice cream']
-------------------------------------------------------------------

程序已結束,退出程式碼為 0