Loading... ## 列表 ### 访问 ``` bicycles = ["trek", "cannondale", "redline", "specialized"] print(bicycles) print(bicycles[0]) print(bicycles[2]) print(bicycles[-1]) print(bicycles[-2]) # 负号代表倒数 message = f"My first bicycle is a {bicycles[0].title()}" print(message) ``` 结果 ``` ['trek', 'cannondale', 'redline', 'specialized'] trek redline specialized redline My first bicycle is a Trek ``` ### 修改添加删除 ``` list = ["honda", "yamaha", "suzuki"] motorcycles = list[:] print(f"origin\t{motorcycles}") motorcycles[0] = "ducati" print(f"replace\t{motorcycles}") motorcycles = list[:] motorcycles.append("ducati") print(f"append\t{motorcycles}") motorcycles = [] motorcycles.insert(0,"ducati") print(f"insert\t{motorcycles}") motorcycles = list[:] del motorcycles[0] ## NOTICE!!! print(f"del\t{motorcycles}") motorcycles = list[:] poped_motorcycle = motorcycles.pop() print(f"pop\t{motorcycles}") print(f"poped out\t{poped_motorcycle}") motorcycles = ["honda", "yamaha", "suzuki", "ducati"] too_expensive = "ducati" motorcycles.remove(too_expensive)##不返回值 print(f"remove\t{motorcycles}") print(f"\nA {too_expensive.title()} is too expensive for me.") ``` 结果 ``` origin ['honda', 'yamaha', 'suzuki'] replace ['ducati', 'yamaha', 'suzuki'] append ['honda', 'yamaha', 'suzuki', 'ducati'] insert ['ducati'] del ['yamaha', 'suzuki'] pop ['honda', 'yamaha'] poped out suzuki remove ['honda', 'yamaha', 'suzuki'] A Ducati is too expensive for me. ``` ### 组织列表 ``` place = ["Paris", "Moscow", "Leningrad", "Stalingrad", "Berlin"] print(len(place)) print(place) print(sorted(place))#sorted()不会改变列表的顺序 print(place) print(sorted(place,reverse=True)) print(place) place.reverse() print(place) place.reverse() print(place) place.sort() print(place) place.sort(reverse=True) print(place) ``` 结果 ``` 5 ['Paris', 'Moscow', 'Leningrad', 'Stalingrad', 'Berlin'] ['Berlin', 'Leningrad', 'Moscow', 'Paris', 'Stalingrad'] ['Paris', 'Moscow', 'Leningrad', 'Stalingrad', 'Berlin'] ['Stalingrad', 'Paris', 'Moscow', 'Leningrad', 'Berlin'] ['Paris', 'Moscow', 'Leningrad', 'Stalingrad', 'Berlin'] ['Berlin', 'Stalingrad', 'Leningrad', 'Moscow', 'Paris'] ['Paris', 'Moscow', 'Leningrad', 'Stalingrad', 'Berlin'] ['Berlin', 'Leningrad', 'Moscow', 'Paris', 'Stalingrad'] ['Stalingrad', 'Paris', 'Moscow', 'Leningrad', 'Berlin'] ``` Last modification:February 14, 2022 © Allow specification reprint Like 如果觉得我的文章对你有用,请留下评论。