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
posted @ 2022-04-08 15:09  NiceTwocu  阅读(25)  评论(0编辑  收藏  举报