如何从列表中打印随机值名称?(python) [英] How to print a random value name from a list?(python)

查看:191
本文介绍了如何从列表中打印随机值名称?(python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说:

list=["A","B","C"]
listitem = random.randint(0,2)

我输入:

print listitem

但是它给出了一个数字,我想要一个字母吗?

but it gives a number and I'd like a letter?

我该怎么做?

推荐答案

您需要使用随机索引来引用列表中的项目.

You need to use the random index to reference the item in your list.

>>> import random
>>> list=["A","B","C"]
>>> listitem = random.randint(0,len(list))
>>> list[listitem]
'A'
>>> listitem = random.randint(0,len(list))
>>> list[listitem]
'B'

或者,如果您不关心索引,只需使用random.choice()例程随机选择一项:

Or, if you don't care about the index, just select an item at random using the random.choice() routine:

>>> random.choice(list)
'B'
>>> random.choice(list)
'B'
>>> random.choice(list)
'A'
>>> random.choice(list)
'C'

这篇关于如何从列表中打印随机值名称?(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆