# 问一个关于python函数式写法的问题

car1.py:

``````from random import random

time = 5
car_positions = [1,1,1]

while time:
# decrease time
time -= 1

print ('')
for i in range(len(car_positions)):
# move car
if random() > 0.3:
car_positions[i] += 1

# draw car
print ('-' * car_positions[i])
``````

car_function.py: (执行的输出不太对)

``````from random import random

def race(state):
draw(state)
if state['time']:
race(run_step_of_race(state))

def draw(state):
print ('')
print ('\n'.join(map(output_car,state['car_positions'])))

def output_car(car_positions):
return '-' * car_positions

def run_step_of_race(state):
return {'time':state['time']-1,'car_positions':move_cars(state['car_positions'])}

def move_cars(car_positions):
return map(lambda x : x+1 if random() > 0.3 else x,car_positions)

race({'time':5,'car_positions':[1,1,1]})

``````

1 个回答

1. `car1.py`中，你是先`car_positions[i] += 1``print('-' * car_positions[i])`，而`car_function.py`中则相反。
2. 也是最大的问题：`car_function.py``move_cars`返回的是`map`对象而不是`list`，因此后面的每次递归`state['car_positions']`都变成了一个`map`对象。解决方法是在`move_cars``return list(map(lambda x: x+1 if random() > 0.3 else x, car_positions))`，就是套一个`list`