1
我有四个我想打印出来的句子,例如。python中不同打印命令的打印顺序
print 'I am here'
print 'I like spring'
print 'My house has two floors'
print 'Sun is bright'
我想让程序在每次运行程序时以不同的顺序打印出来。哪种做法最好?
感谢,
我有四个我想打印出来的句子,例如。python中不同打印命令的打印顺序
print 'I am here'
print 'I like spring'
print 'My house has two floors'
print 'Sun is bright'
我想让程序在每次运行程序时以不同的顺序打印出来。哪种做法最好?
感谢,
我喜欢random.shuffle
这一点。它需要一个列表并将其随机排序(如一副纸牌)。然后,您可以像打印任何其他列表一样打印它们(使用for-loop)。
这将要求您先将它们放到一个字符串列表中,而不是仅仅具有打印语句。
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()))
将它们放入一个数组中,随机洗刷数组,然后按顺序打印数组。 – Barmar