generate list of strings

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ss30
    New Member
    • Aug 2008
    • 6

    generate list of strings

    Hi,

    I'm trying to generate a list of random digits with no repeats. So far i have:

    a = random.sample(r ange(0, 1), n)

    which generates a list of random digits in a list with no repeat such as [1, 3, 5, 9] where n is 4.

    However, i need it to produce a list of string of digits with no repeats, such as ['1', '3', '5', '9']. Is there any simple way to do this?

    Thankyou for reading.
  • realin
    Contributor
    • Feb 2007
    • 254

    #2
    i could get this result

    Code:
    '[10, 0, 5, 1]'
    outta this code 
    >>> str(random.sample(range(0,11),4))
    i know that may be different, but this is what i learnt today cause i just started with python :)

    cheers !!

    Comment

    • Laharl
      Recognized Expert Contributor
      • Sep 2007
      • 849

      #3
      If you want to make each element a string, the simplest way is to generate the list of digits the way you did and then use a list comprehension or loop to convert each to a string.

      Code:
      a = [str(elem) for elem in a] #list comprehension, I'm not going to type out the loop version, as it's almost identical

      Comment

      • Thekid
        New Member
        • Feb 2007
        • 145

        #4
        This will print out 4 random numbers in the range(1,44). It's easy to adjust as well:

        Code:
        import random
        randlist=[]
        while (randlist.__len__() <= 4):
          b =random.randint(1,44)
          if not b in randlist:
             randlist.append(b)
        print randlist
        Credit to kaarthikeyaprey an for that code: http://bytes.com/forum/thread827473.html

        Or is it that you need the answer to print out with quotes around each number?

        Comment

        Working...