<分区>
我有四个句子要打印出来,例如。
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 循环)。
这将要求您首先将它们放入字符串列表中,而不仅仅是打印语句。
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()))
关于python - python中不同打印命令的打印顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20474835/
相关文章:
python - 如何在networkx中使用python随机排列图的节点?
python - 如何通过 python/pyqt 创建 Windows 7 跳转列表?
python - PowerShell中的virtualenv?
python - Python 模块中的命名空间与 Flask 发生冲突
python - 将可选参数传递给例如 ax.set(ylabel=...)
python - 值错误: Invalid parameter model for estimator CountVectorizer when using GridSearch parameters
python - asyncpg.exceptions.InvalidAuthorizationSpecificationError Python PostgreSQL