numbers = list(range(1,6))
print(numbers)
num_odds= list(range(1,11,2))
print(num_odds)
num_sqr=[]
for num in range(1,11):
num_sqr.append(num**2)
print(num_sqr)
digits = list(range(1,21))
print(max(digits),min(digits),sum(digits))
编写一行代码来完成列表的生成。
例:使用一行代码完成上面的平方数列表的构建:
squares = [value**2 for value in range(1,11)]
print(squares)
#4-3
print("4-3")
for i in range(1,21):
print(i,end=" ")
#4-4
# for i in range(1,1000001):
# print(i,end=" ")
print("\n4-5")
nums = list(range(1,1000001))
print(max(nums),min(nums),sum(nums))
#4-6
print("4-6")
odds = [i for i in range(1,21,2)]
print(odds)
#4-7
print("4-7")
num_by_three = [i for i in range(3,31) if i % 3 == 0]
print(num_by_three)
#4-8
print("4-8")
list = []
for i in range(1,11):
list.append(i**3)
print(list)
#4-9
print("4-9")
num_triple = [i**3 for i in range(1,11)]
print(num_triple)
num = list(range(1,11))
print(num)
print(num[1:5])
print(num[:4])
print(num[6:])
print(num[-3:])
同时省略起始和终止索引 [ : ]
num = list(range(1,11))
num1 = num[:]
print(num)
print(num1)
num.append(18)
print(num)
print(num1)
若使用变量名直接赋值的方法,则不会创建一个新列表,两个变量名都指向一个列表,对列表进行操作时不管使用哪个变量名,列表都会进行改变。
num = list(range(1,11))
num1 = num
print(num)
print(num1)
num.append(18)
print(num)
print(num1)
#4-10
print("4-10")
num = list(range(1,21))
print(num)
print(num[:3])
print(num[int(len(num)/3):int(len(num)/3)+3])
print(num[-3:])
#4-11
print("4-11")
pizzas = ['a','b','c','d']
friend_pizzas = pizzas[:]
pizzas.append('ee')
friend_pizzas.append('ff')
for pizza in pizzas:
print(f"My favorate pizza is {pizza}")
for friend_pizza in friend_pizzas:
print(f"My friend's favorate pizza is {friend_pizza}")
不可修改的列表称之为元组
使用圆括号定义: tuple = (10,20)
- 元组中的变量值和元组的长度都不能改变。
- 使用for循环对元组中的值进行遍历。
- 若需要存储的一组值在程序的整个生命周期中都要保持不变,则可以使用元组。
foods = ('noodles','soup','dumplings','hamburger','chips')
for food in foods:
print(food)
print("\n")
# error!!
#food[1]='rice'
foods = ('water','chicken','dumplings','hamburger','chips')
for food in foods:
print(food)