[英]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']
Problem area where i want the distance to go directly after the directions are revealed. 问题区域,我希望距离在显示方向后直接走。
Each direction should only appear once. 每个方向只能出现一次。
for i in range(x):
print('You can move ' + ''.join(" ".join(random.sample(f, 1) + random.sample(dis, 1 )))+" meters")
So essentially I am trying to generate strings that tell the user what directions they can move in and how far away it is based on random selection. 因此,从本质上讲,我试图基于用户的随机选择来生成字符串,以告知用户他们可以向哪个方向移动以及距离多远。 The program however posed a challenge to me as I tried to get it to join the direction and distance together.Based on the number generated by
x
the program would place the associated directions and distances together. 但是,当我尝试将方向和距离连接在一起时,该程序对我构成了挑战。基于
x
生成的数字,程序会将相关的方向和距离放在一起。
For example: using this code produces this: 例如: 使用此代码将产生以下结果:
print('You can move ' + ''.join(" ".join(random.sample(f, x) + random.sample(dis, x )))+" meters")
You can move Forward Left Right 9 4 5 meters 您可以向前移动左右9 4 5米
The code under the section Code around the problem used a for loop that takes the randomly-generated number from x
and makes it loop for that many times. 关于问题的代码部分下的代码使用了for循环,该循环从
x
中获取随机生成的数字,并使它循环多次。 I initially thought that this would be the final solution , however, i tried running it and the directions appeared more than once (which is a bit more than i had hoped for).Really and truly i would just like a solution that gives the direction and distance only once and in a format such as this: 最初我以为这是最终的解决方案,但是我尝试运行它,并且方向出现了多次(这比我希望的要多)。确实,我真的很想提供方向的解决方案和距离仅一次,并采用以下格式:
You can move Right 5 meters 您可以向右移动5米
You can move Forward 9 meters 您可以前进9米
You can move Left 8 meters 您可以向左移动8米
How about this: 这个怎么样:
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)
You can use random.sample()
method like in your example. 您可以像示例中一样使用
random.sample()
方法。 Just use zip()
method to tie randomly sampled values from dis and f together: 只需使用
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))
This will print for example: 例如,将打印:
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.