有两段python代码,运行应该说会一致的,但是没有达到一致的效果,不知道问题在哪,其中car1.py输出是对的.
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]})
为什么呢???
def move_cars(car_positions):
return map(lambda x : x+1 if random() > 0.3 else x,car_positions)
改为:
def move_cars(car_positions):
return list(map(lambda x : x+1 if random() > 0.3 else x,car_positions))
Python2中,map直接返回元素列表
Python3中,map函数返回一个map类型对象。
也就是python2和python3版本的问题,
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 list(map(lambda x: x + 1 if random() > 0.3 else x, car_positions)) #这个地方应该返回list,而不是map
race({'time': 5, 'car_positions': [1, 1, 1]})
放在python2是没事的对吧
@君君的BigHeadDaddy: python2返回的是列表 https://www.runoob.com/python/python-func-map.html
因为你要用到list,所以使用list将map转换成list就行了,你用在线编辑器试试,http://www.pythontip.com/coding/run
@E行者: 可以可以,
建议在博问重新提交一下问题
– dudu 4年前@dudu: 不提倡挂外链接吗
– 君君的BigHeadDaddy 4年前@dudu: 悬赏的豆豆该怎样给回答人呢...点不了选项
– 君君的BigHeadDaddy 4年前@君君的BigHeadDaddy: 结帖时输入园豆数量
– dudu 4年前