简体   繁体   English

打印由随机数选择的变量

[英]Print a variable selected by a random number

I have a list of names, and I would like my program to randomly select one of those names. 我有一个名单,我希望我的程序随机选择其中一个名称。 I tried using the following: 我尝试使用以下内容:

import random


def main():

    Arkansas = 1
    Manchuria = 2
    Bengal = "3"
    Baja_California = 4
    Tibet = 5
    Indonesia = 6
    Cascade_Range = 7
    Hudson_Bay = 8
    High_Plains = 9
    map = random.randrange(1, 10)
    print(map)

main()

I also tried making each of the numbers as strings, using the eval() function for randrange() , but none of this worked. 我也尝试使用randrange()eval()函数将每个数字作为字符串,但这些都randrange()

Don't assign numbers OR strings. 不要指定数字或字符串。 Use a list. 使用列表。

choices = ['Arkansas', 'Manchuria', 'Bengal', 'Baja California']   # etc.

Then take a random.choice 然后random.choice

random_choice = random.choice(choices)

Another option is to use a dictionary. 另一种选择是使用字典。

my_dict = {1:"Arkansas", 2:"Manchuria", 3:"Bengal",
           4:"Baja California", 5:"Tibet", 6:"Indonesia", 
           7:"Cascade Range", 8:"Hudson Bay", 9:"High Plain"}
map = random.randrange(1, 10)
print(my_dict[map])

Using a list and random.choice() is probably the better option (easier to read, less bytes), but if you have to assign numbers, this will work. 使用list和random.choice()可能是更好的选择(更容易阅读,更少的字节),但如果你必须分配数字,这将是有效的。

I do this by assigning a random floating point number to a string item in a list and sort the list alphabetically. 我这样做是通过为列表中的字符串项分配随机浮点数并按字母顺序对列表进行排序。 Each time you will get a different output. 每次你会得到不同的输出。 I do the same in Excel and OpenOffice Calc actually. 我实际上在Excel和OpenOffice Calc中也这样做。 Simple. 简单。

#!/usr/bin/python
# -*- coding: utf-8 -*-

import random

L=['Arkansas', 'Manchuria', 'Bengal', 'Baja California', 'Tibet', 'Indonesia', 'Cascade_Range', 'Hudson Bay', 'High_Plains']

tmp=[]

for item in L:
    item=str(random.random())+'|'+item
    tmp.append(item)

tmp.sort()

for item in tmp:
    print item[item.find('|')+1:]

Output 1 输出1

Bengal
Manchuria
Tibet
Indonesia
High_Plains
Arkansas
Baja California
Cascade_Range
Hudson Bay

Output 2 输出2

Bengal
Baja California
Manchuria
Tibet
Arkansas
High_Plains
Cascade_Range
Hudson Bay
Indonesia

if you want to get just one name you can break the loop: 如果你想得到一个名字就可以打破循环:

for item in tmp:
    print item[item.find('|')+1:]
    break

Output 1 输出1

Baja California

Output 2 输出2

Cascade_Range

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

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