views:

68

answers:

1

Hi SO,

This is a kind of newbie question, but I couldn't find a solution. I read a list of strings from a file, and try to get a random, 5 element sample with random.sample, but the resultung list only contains characters. Why is that? How can I get a random sample list of strings?

This is what I do:

    names = random.sample( open('names.txt').read(), 5 )
    print names

This gives a five element character list like:

['\x91', 'h', 'l', 'n', 's']

If I omit the random.sample part, and print the list, it prints out every line of the file, which is the expected behaviour, and proves that the file is read OK.

+2  A: 

If the names are all on seperate lines, ry the following:

names = random.sample(open('names.txt').readlines(), count)
print names

Essentially you are going wrong because you need to pass an interable to random.sample(). When you pass a string it treats it like a list. If you're names are all on one line, you need to use split() to pull them apart and pass that list to random.sample().

jkp
Thank you. Now let this question be faded into the unknown :D
Tamás Szelei