简体   繁体   中英

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.

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(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.

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. 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

Bengal
Manchuria
Tibet
Indonesia
High_Plains
Arkansas
Baja California
Cascade_Range
Hudson Bay

Output 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

Baja California

Output 2

Cascade_Range

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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