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

2024-04-26 11:15:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有四个句子要打印出来

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

我想让程序每次运行时都按不同的顺序打印出来。哪种方法最好?你知道吗

谢谢你


Tags: 程序hereismyamlike句子house
1条回答
网友
1楼 · 发布于 2024-04-26 11:15:57

我喜欢这个。它获取一个列表并将其随机排列(就像一副牌)。然后,您可以像打印任何其他列表一样打印它们(使用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()))

相关问题 更多 >