Python基础二–容器型数据类型(1)
容器型数据类型:是用一个变量保存多个数据
容器型数据类型主要有:
- 列表(list)
- 元组(tuple)
- 集合(set)
- 字典(dict)
列表的创建
nums = [1,2,3,4,5]
``
![在blog.csdnimg.cn/0745b0cb790048beada369e6d0b58c93.png
```python
rules = ['祖国万岁,人民万岁','好好学习,天天向上']
nums.append(6)
rules.append('100周年')
nums.insert(2,7)
rules.insert(2,'你好')
nums.pop()
rules.pop()
列表的遍历
nums = [12,23,34,55,66]
print(nums[2],nums[-5])
元素的替换
nums[2]=100
print(nums)
列表的操作
len() –>length—>给出列表中元素的个数(长度)
for i in range(len(nums)):
nums[i]=10
print(nums[i])
print(nums)
for num in nums:
num = 1100
print(num)
print(nums)
enumerate() –>enumerate枚举
for i,x in enumerate(nums):
print(i,x)
print(nums)
列表相关例题
循序渐进学列表
-
计算60000次色子的1,2,3,4,5,6点分别出现的次数 不用列表写程序为 import random
f1, f2, f3, f4, f5, f6 = 0, 0, 0, 0, 0, 0, 0
total = 0
while total < 60000:
total +=1
a = random.randrange(1, 7)
if a == 1:
f1 += 1
elif a == 2:
f2 += 1
elif a == 3:
f3 += 1
elif a == 4:
f4 += 1
elif a == 5:
f5 += 1
else:
f6 += 1
print(f"一点次数{f1},二点次数{f2},三点次数{f3},四点次数{f4},五点次数{f5},六点次数{f6}")
用列表方法解决为
fs = [0, 0, 0, 0, 0, 0]
for _ in range(60000):
face = random.randrange(7)
fs[face - 1] += 1
print(fs)
print('-' * 30)
for i, x in enumerate(fs):
print(f'{i + 1}点的次数{x}')
- 输入10个整数,计算平均值和方差,找出最大值和最小值
公式为
nums = []
for _ in range(10):
temp = int(input('请输入数据: '))
nums.append(temp)
print(nums)
mean_value = sum(nums) / len(nums)
total = 0
for num in nums:
total += (num - mean_value) ** 2
var_value = total / (len(nums) - 1)
std_value = var_value ** 0.5
max_value, min_value = max(nums), min(nums)
print(f'均值: {mean_value}')
print(f'方差: {var_value}')
print(f'标准差: {std_value}')
print(f'极差(全距): {max_value - min_value}')
|