在python中打印不同打印命令的顺序

时间:2013-12-09 15:54:53

标签: python

我有四个句子要打印出来,例如。

print 'I am  here'
print 'I like spring'
print 'My house has two floors'
print 'Sun is bright'

我想让程序在每次运行程序时以不同的顺序打印出来。哪种方法最好?

谢谢,

1 个答案:

答案 0 :(得分:5)

我喜欢random.shuffle。它需要一个列表并将其随机播放(如一副牌)。然后,您可以像任何其他列表一样打印出来(使用for循环)。

这将要求您首先将它们放入字符串列表中,而不是仅使用print语句。

import random
ss = ['I am here', 'I like spring', 'My house has two floors', 'Sun is bright']
random.shuffle(ss)
for s in ss:
    print s

这是一种可爱的方式,在一行中做到这一点。它使用随机键上的排序来混洗列表,然后使用.join将四个字符串与换行符组合......然后将其打印出来。我建议你使用我的第一个建议,而不是这个。

import random
print '\n'.join(sorted(['I am here', 'I like spring', 'My house has two floors', 'Sun is bright'], key=lambda *args: random.random()))