import random total=[] for i in range(30): total=list.append(random.randint(1,150)) print('列表',total)为什么输出的列表是空值
时间: 2024-03-15 08:45:38 浏览: 14
在您的代码中,第4行 `total=list.append(random.randint(1,150))` 出现了问题。
`list.append()` 方法会直接修改 `list` 对象本身,并不会返回一个新的列表对象。因此,您不应该将其赋值给 `total`。正确的写法应该是:
```
import random
total=[]
for i in range(30):
total.append(random.randint(1,150))
print('列表',total)
```
这样,每次循环时,都会将一个随机整数添加到 `total` 列表中,最终输出的就是一个包含 30 个随机整数的列表。
相关问题
解释每条语句作用import random import matplotlib.pyplot as plt def roll_dice(): #模拟掷骰子 roll = random.randint(1, 6) return roll def main(): #主函数 total_time = 1000 # 初始化列表 result_list = [0] * 11 # 初始化点数列表 roll_list = list(range(2, 13)) roll_dict = dict(zip(roll_list, result_list)) # 记录骰子1的的结果 roll1_list = [] roll2_list = [] for i in range(total_time): roll1 = roll_dice() roll2 = roll_dice() roll1_list.append(roll1) roll2_list.append(roll2) # 获取点数存储到对应次数位置 for j in range(2, 13): if (roll1 + roll2) == j: roll_dict[j] += 1 break for i, result in roll_dict.items(): print('点数{}的次数{},频率:{}'.format(i, result, result / total_time)) # 数据可视化 x = range(1, total_time + 1) plt.scatter(x, roll1_list, c='red', alpha=0.5) plt.scatter(x, roll2_list, c='green', alpha=0.5) plt.show() if __name__ == '__main__': main()
1. `import random`: 导入Python内置的`random`模块,用于生成随机数。
2. `import matplotlib.pyplot as plt`: 导入`matplotlib`模块中的`pyplot`子模块,用于生成数据可视化图表。
3. `def roll_dice():`:定义一个函数`roll_dice()`,用于模拟掷骰子的过程。
4. `roll = random.randint(1, 6)`: 生成1~6之间的随机整数,模拟骰子掷出的结果。
5. `return roll`: 返回骰子掷出的结果。
6. `def main():`: 定义主函数`main()`,用于实现主要的骰子模拟和数据可视化过程。
7. `total_time = 1000`: 设定掷骰子的总次数为1000次。
8. `result_list = [0] * 11`: 初始化一个长度为11的列表,用于记录掷骰子后每个点数出现的次数。
9. `roll_list = list(range(2, 13))`: 初始化一个包含骰子点数2~12的列表。
10. `roll_dict = dict(zip(roll_list, result_list))`: 将骰子点数列表和次数列表打包成字典,用于记录每个点数出现的次数。
11. `roll1_list = []`和`roll2_list = []`: 初始化两个空列表,用于记录每次掷骰子的结果。
12. `for i in range(total_time):`: 循环掷骰子的总次数。
13. `roll1 = roll_dice()`和`roll2 = roll_dice()`: 分别模拟掷两个骰子的结果。
14. `roll1_list.append(roll1)`和`roll2_list.append(roll2)`: 将每次掷骰子的结果添加到对应的列表中。
15. `for j in range(2, 13):`: 循环每个可能的点数。
16. `if (roll1 + roll2) == j:`: 如果掷出的两个骰子的点数之和等于当前点数。
17. `roll_dict[j] += 1`: 将当前点数出现次数加1。
18. `break`: 跳出循环,因为已经确定了当前点数的出现次数。
19. `for i, result in roll_dict.items():`: 遍历字典中的每个元素,获取每个点数出现的次数和频率。
20. `print('点数{}的次数{},频率:{}'.format(i, result, result / total_time))`: 打印每个点数出现的次数和频率。
21. `x = range(1, total_time + 1)`: 生成一个长度为total_time的序列,用于表示每次掷骰子的次数。
22. `plt.scatter(x, roll1_list, c='red', alpha=0.5)`和`plt.scatter(x, roll2_list, c='green', alpha=0.5)`: 用散点图的方式将每次掷骰子的结果可视化,其中红色散点表示第一个骰子的结果,绿色散点表示第二个骰子的结果。
23. `plt.show()`: 显示可视化图表。
24. `if __name__ == '__main__':`: 判断当前脚本是否为主程序。
25. `main()`: 如果当前脚本是主程序,则执行主函数`main()`。
使用了遗传算法对函数 f(x)=xsin(10πx)+1.0 进行优化,求出其最大值,其中 x 属于[-1,2]。
好的,我来回答你的问题。以下是代码实现:
```python
import random
import math
# 定义适应度函数
def fitness(x):
return x * math.sin(10 * math.pi * x) + 1.0
# 定义选择算法
def selection(population):
fitness_list = [fitness(x) for x in population]
total_fitness = sum(fitness_list)
probability_list = [fitness / total_fitness for fitness in fitness_list]
cum_probability_list = []
cum_probability = 0.0
for probability in probability_list:
cum_probability += probability
cum_probability_list.append(cum_probability)
selected_population = []
for i in range(len(population)):
r = random.random()
for j in range(len(cum_probability_list)):
if r < cum_probability_list[j]:
selected_population.append(population[j])
break
return selected_population
# 定义交叉算法
def crossover(population, crossover_rate):
offspring_population = []
for i in range(len(population) // 2):
parent1 = population[i * 2]
parent2 = population[i * 2 + 1]
if random.random() < crossover_rate:
crossover_point = random.randint(1, len(parent1) - 2)
offspring1 = parent1[:crossover_point] + parent2[crossover_point:]
offspring2 = parent2[:crossover_point] + parent1[crossover_point:]
else:
offspring1 = parent1
offspring2 = parent2
offspring_population.append(offspring1)
offspring_population.append(offspring2)
return offspring_population
# 定义变异算法
def mutation(population, mutation_rate):
mutated_population = []
for individual in population:
mutated_individual = []
for gene in individual:
if random.random() < mutation_rate:
mutated_gene = gene + random.uniform(-0.1, 0.1)
if mutated_gene < -1:
mutated_gene = -1
elif mutated_gene > 2:
mutated_gene = 2
mutated_individual.append(mutated_gene)
else:
mutated_individual.append(gene)
mutated_population.append(mutated_individual)
return mutated_population
# 初始化种群
def initialize_population(population_size):
population = []
for i in range(population_size):
individual = [random.uniform(-1, 2) for j in range(10)]
population.append(individual)
return population
# 主函数
def main():
population_size = 50
generations = 100
crossover_rate = 0.8
mutation_rate = 0.2
population = initialize_population(population_size)
for i in range(generations):
population = selection(population)
population = crossover(population, crossover_rate)
population = mutation(population, mutation_rate)
best_individual = max(population, key=fitness)
print("最大值为:", round(fitness(best_individual), 6))
print("最优解为:", best_individual)
if __name__ == '__main__':
main()
```
注:本代码使用了遗传算法对函数 f(x)=x*sin(10π*x)+1.0 进行优化,求出其最大值。其中,种群规模为50,迭代次数为100次,交叉概率为0.8,变异概率为0.2。在运行代码时,会输出最大值和最优解。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)