列表由一系列按特定顺序排列的元素组成,元素之间可以没有任何关系,在Python
中,用[]
表示列表,用,
来分隔元素
languages = [‘Java‘, ‘C‘, ‘Python‘, ‘PHP‘]
print(languages)
print(languages[0]) //第一个元素
print(languages[-1]) //最后一个元素
print(languages[-2]) //倒数第二个元素
languages[0] = ‘JS‘
print(languages)
languages = [‘Java‘, ‘C‘, ‘Python‘]
languages.append(‘PHP‘)
print(languages)
languages = [‘Java‘, ‘C‘, ‘Python‘]
languages.insert(0, ‘PHP‘)
print(languages)
del languages[0]
print(languages)
languages = [‘Java‘, ‘C‘, ‘Python‘]
language = languages.pop()
print(languages)
print(language)
languages = [‘Java‘, ‘C‘, ‘Python‘]
language = languages.pop(0)
print(languages)
print(language)
# 方法remove只删除第一个指定的值,多次需要使用循环
languages = [‘Java‘, ‘C‘, ‘Python‘]
languages.remove(‘Java‘)
print(languages)
languages = [‘Java‘, ‘C‘, ‘Python‘, ‘PHP‘]
languages.sort()
print(languages)
languages = [‘Java‘, ‘C‘, ‘Python‘, ‘PHP‘]
languages.sort(reverse=True)
print(languages)
languages = [‘Java‘, ‘C‘, ‘Python‘, ‘PHP‘]
print(sorted(languages))
languages = [‘Java‘, ‘C‘, ‘Python‘, ‘PHP‘]
print(sorted(languages,reverse=True))
languages = [‘Java‘, ‘C‘, ‘Python‘, ‘PHP‘]
languages.reverse()
print(languages)
languages = [‘Java‘, ‘C‘, ‘Python‘, ‘PHP‘]
print(len(languages))
languages = [‘Java‘, ‘C‘, ‘Python‘, ‘PHP‘]
for language in languages:
print(languages)
for value in range(1,5):
print(value)
numbers = list(range(1,6))
print(numbers)
even_numbers = list(range(2,11,2))
print(even_numbers)
squares = []
for value in range(1,11):
squares.append(value**2)
print(squares)
numbers = range(1,11)
print(min(numbers))
print(max(numbers))
print(sum(numbers))
# for循环和doing合成一句代码
sequares = [value**2 for value in range(1,11)]
print(sequares)
# 指定要使用的第一个元素索引和最后一个元素的索引+1
languages = [‘Java‘, ‘C‘, ‘Python‘, ‘PHP‘, ‘Android‘]
print(languages[0:3])
print(languages[1:4])
# 如果未指定起始索引,将自动从列表开头开始
languages = [‘Java‘, ‘C‘, ‘Python‘, ‘PHP‘, ‘Android‘]
print(languages[:4])
# 如果未指定终止索引,将终止与列表末尾
languages = [‘Java‘, ‘C‘, ‘Python‘, ‘PHP‘, ‘Android‘]
print(languages[2:])
# 负数索引返回离列表末尾相应距离的元素,可用于切片
languages = [‘Java‘, ‘C‘, ‘Python‘, ‘PHP‘, ‘Android‘]
print(languages[-3:]) # 输出最后三个元素
languages = [‘Java‘, ‘C‘, ‘Python‘, ‘PHP‘, ‘Android‘]
for language in languages[:3]:
print(language)
# 创建包含整个列表的切片,省略起始和终止索引,即复制整个列表
languages = [‘Java‘, ‘C‘, ‘Python‘, ‘PHP‘, ‘Android‘]
my_languages = languages[:]
print(my_languages)
# 不可变的列表称为元组,元素使用圆括号来标识
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
for dimension in dimensions:
print(dimension)
dimensions = (200, 50)
print(dimensions)
dimensions = (500, 100)
print(dimensions)
原文:https://www.cnblogs.com/maggieq8324/p/14243913.html