目录导航
双引号和单引号都可以。
【实例】:
country = ['china',"america",'russia'] print(country) print(country[1])
【运行结果】:
['china', 'america', 'Russia'] america
【实例】:
country = ['china','america','russia'] print(country) country[1] = 'england' print(country)
【运行结果】:
['china', 'america', 'russia'] ['china', 'england', 'russia']
在列表尾部添加:
【实例】:
country = ['china','america','russia'] print(country) country.append('england') print(country)
【运行结果】:
['china', 'america', 'russia'] ['china', 'america', 'russia', 'england']
在列表任意位置添加:
使用方法insert() 可在列表的任何位置添加新元素,第一个参数为添加到的位置。若为0,则表示添加到列表首部。
【实例】:
country = ['china','america','russia'] print(country) country.insert(2,'england') print(country)
【运行结果】:
['china', 'america', 'russia'] ['china', 'america', 'england', 'russia']
在列表首部添加:
【实例】:
country = ['china','america','russia'] print(country) country.insert(0,'england') print(country)
【运行结果】:
['china', 'america', 'russia'] ['england', 'china', 'america', 'russia']
使用del语句删除,参数为删除位置。
【实例】:
country = ['china','america','russia'] print(country) del country[1] print(country)
【运行结果】:
['china', 'america', 'russia'] ['china', 'russia']
使用pop弹出列表末尾元素。
【实例】:
country = ['china','america','russia'] pop_country = country.pop() print(country) print(pop_country)
【运行结果】:
['china', 'america'] russia
使用pop弹出任意位置元素。
【实例】:
country = ['china','america','russia'] pop_country = country.pop(1) print(country) print(pop_country)
【运行结果】
['china', 'russia'] america
使用remove根据值来删除元素。
【实例】:
country = ['china','america','russia'] country.remove('america') print(country)
【运行结果】:
['china', 'russia']
使用sort对列表进行永久排序,按字母顺序排序。
【实例】:
country = ['china','america','russia'] country.sort() print(country)
【运行结果】:
['america', 'china', 'russia']
在sort方法中添加参数reverse=True,即可按相反顺序排列。
【实例】:
country = ['china','america','russia'] country.sort(reverse=True) print(country)
【运行结果】:
['russia', 'china', 'america']
使用sorted()对列表临时排序。
【实例】:
country = ['china','america','russia'] print(sorted(country)) print(country)
【运行结果】:
['america', 'china', 'russia'] ['china', 'america', 'russia']
反转列表顺序。
【实例】:
country = ['china','america','russia'] country.reverse() print(country)
【运行结果】:
['russia', 'america', 'china']
【实例】:
country = ['china','america','russia'] print(country) print(len(country))
【运行结果】:
['china', 'america', 'russia'] 3
o(* ̄▽ ̄*)ブ 谢谢观看,希望对你有帮助!
标签:Python,country,列表,china,print,america,russia From: https://www.cnblogs.com/yihong-song/p/16816388.html