1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Python help needed.. how to get this random to work?

Discussion in 'General Programming Chat' started by matt1972, Nov 25, 2011.

  1. matt1972

    matt1972 Regular Member

    Joined:
    Nov 19, 2009
    Messages:
    499
    Likes Received:
    206
    Occupation:
    To make money
    Location:
    192.168.0.1
    I've got this..

    Word_List = ['for', 'about', 'how']

    I call that with this.. random.choice(Word_List)

    What I want to do is something like this...

    Word_List = ['for', 'about', 'how'] + ['house', 'car', 'tree']

    and have it take one random from the first one and one random from the second one. How would I get that to work so my outputs would be something like this?

    for car
    how tree
    about house
    etc..
     
  2. kassman

    kassman Newbie

    Joined:
    Sep 2, 2011
    Messages:
    19
    Likes Received:
    3
    you can do it always like this

    Word_List = ['for', 'about', 'how']
    Word_List2 = ['a', 'b', 'c']

    combined = random.choice(Word_list) + " " + random.choice(Word_list2)

    if you want to have it unique
    worda = random.choice(Word_list)
    wordb = random.choice(Word_list2)
    combined = worda + " " + wordb
    Word_List.remove(worda)
    Word_List2.remove(wordb)

    or if you want to end up with unique list and there's a lot of them... going let's say in foreach loop you can do like that:

    #define empty one to hold new values combined together
    list_full_of_uniqueness = []
    foreach word in Word_list:
    #assign new word from wl2
    wordb = random.choice(Word_list2)
    # one from wl1 is used in loop so we just need to remove it from the wl2
    Word_list2.remove(wordb)
    #combine it and put into new list
    combined = word + " " + wordb
    list_full_of_uniquness.append(combined)

    now if you'd do foreach combined in list_full_of_uniquness: print combined
    you'd end up with something like you wrote above so:
    for car
    how tree
    about house

    if you don't need it unique and want to spin a lot simply delete wordlistx.remove() calls.
     
    • Thanks Thanks x 1
  3. Deusdies

    Deusdies Regular Member

    Joined:
    May 22, 2009
    Messages:
    261
    Likes Received:
    190
    Code:
    
    from random import randrange
    
    words1 = ['first','second','third']
    words2 = ['fourth','fifth','sixth']
    
    pick_one = randrange(0, len(words1)) # or words2
    
    selected_words = words1[pick_one] + words2[pick_one]
    
    Nice and simple :)
     
    • Thanks Thanks x 1