import random select_parents(crowding_distance): # 从拥挤度距离中随机选择两个父代个体 parent_indices = [] for i in range(2): random_index = random.randint(0, len(crowding_distance) - 1) parent_indices.append(random_index) return parent_indices这段代码如何定义成一个函数
时间: 2024-01-08 09:04:32 浏览: 69
随机函数代码
可以这样定义成一个函数:
```python
import random
def select_parents(crowding_distance):
# 从拥挤度距离中随机选择两个父代个体
parent_indices = []
for i in range(2):
random_index = random.randint(0, len(crowding_distance) - 1)
parent_indices.append(random_index)
return parent_indices
```
使用时,只需要将拥挤度距离作为参数传入即可:
```python
crowding_distance = [3, 1, 4, 2, 5]
parent_indices = select_parents(crowding_distance)
print(parent_indices) # 输出随机选择的两个父代个体的索引
```
阅读全文