开发者

Pick a Random Word On a Single Line In Python?

开发者 https://www.devze.com 2023-01-30 01:02 出处:网络
How would I pick a single line and pick all the words on that line and then print them t开发者_运维百科o the screen using a set. This is what I have so far:

How would I pick a single line and pick all the words on that line and then print them t开发者_运维百科o the screen using a set. This is what I have so far:

import random

test = ['''
line 1
line 2
line 3
line 4
line 5
line 6
''']
print (random.choice(test))


I think this does exactly what you're asking:

print random.choice(test[0].split('\n'))
line 5

I have a feeling you're looking to do a little more than that, though.


I suspect you want to pick them randomly without replacement; if all you do is pick words randomly, with something like

do until set empty
   prick a random word and print it

it would (a) not terminate, and (b) repeat words on average every 1/n times for n words.

It would be tempting to use a Python set, but inconveniently there's no obvious way to pick a random item from the set since it's not ordered. (You might make a case that set#pop will work since it takes the arbitrary next item, but if I were grading I wouldn't give that full credit.) On the other hand, the description says a set.

So I'd do something like this:

First put the items into a list. Note that what you have puts one string with 10 lines into the list,, that is your list has length 1. I'd bet you're better off initializing like

words = [ "test 1","test 2" # and so on
]

Next, select your items using choice as

word = random.choice(words)

Print it

print word

and remove it from the list

words.remove(word)

Put that in a loop that continues until you run out of words. You get something like:

>>> import random
>>> words = ['a', 'b', 'c' ]
>>> while len(words) > 0:
...    word = random.choice(words)
...    print word
...    words.remove(word)
... 
b
a
c

gnibbler points out that you could also have

import random
words = [ ... ]
shuf = random.shuffle(words)
for i in shuf: 
   print i

but that doesn't treat the list as a set; it depends on there being an implicit order set by shuffle.

0

精彩评论

暂无评论...
验证码 换一张
取 消