繁体   English   中英

我想弄清楚怎么做

[英]I want to figure out how to make t

解决问题的代码

import random 

from random import randint 

x = random.randint(1,3)

dis = {'5','6','9','4','7','8'}

f = ['Left' , 'Right' , 'Forward']

问题区域,我希望距离在显示方向后直接走。

每个方向只能出现一次。

for i in range(x):

    print('You can move ' + ''.join(" ".join(random.sample(f, 1) + random.sample(dis, 1 )))+" meters")

概观

因此,从本质上讲,我试图基于用户的随机选择来生成字符串,以告知用户他们可以向哪个方向移动以及距离多远。 但是,当我尝试将方向和距离连接在一起时,该程序对我构成了挑战。基于x生成的数字,程序会将相关的方向和距离放在一起。

例如: 使用此代码将产生以下结果:

print('You can move ' + ''.join(" ".join(random.sample(f, x) + random.sample(dis, x )))+" meters")

您可以向前移动左右9 4 5米

关于问题的代码部分下的代码使用了for循环,该循环从x中获取随机生成的数字,并使它循环多次。 最初我以为这是最终的解决方案,但是我尝试运行它,并且方向出现了多次(这比我希望的要多)。确实,我真的很想提供方向的解决方案和距离仅一次,并采用以下格式:

您可以向右移动5米

您可以前进9米

您可以向左移动8米

这个怎么样:

import random


dis = ['5','6','9','4','7','8']
f = ['Left' , 'Right' , 'Forward']

f_count = len(f)
for i in range(0, f_count):
    x = random.randint(0, len(f)-1)
    y = random.randint(0, len(dis)-1)
    dir = f[x]
    print('You can move ' + dir + " "+ dis[y] + " meters")
    f.pop(x)
    dis.pop(y)

您可以像示例中一样使用random.sample()方法。 只需使用zip()方法将来自dis和f的随机采样值绑定在一起:

import random

dis = ['5', '6', '9', '4', '7', '8']
f = ['Left', 'Right', 'Forward']

for direction, d in zip(random.sample(f, len(f)), random.sample(dis, len(f))):
    print('You can move {} {} meters'.format(direction, d))

例如,将打印:

You can move Forward 9 meters
You can move Left 5 meters
You can move Right 8 meters

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM