我正在尝试编写此代码 我以随机顺序打印出3行数字1-6。但是,有什么方法可以使它打印1到6之间的数字对,而不是随机打印6个数字? 示例:当前打印:
[1, 6, 5, 3, 4, 2]
所需打印:
[1, 6]
[5, 3]
[4, 2]
代码:
@bot.command()
async def teams(ctx, players):
await ctx.send("Ido - 1: Yona - 2: Noam - 3: Gil - 4: Liel - 5: Yuval - 6:")
await ctx.send('Calculating...')
from random import shuffle
sequence1 = [i for i in range(1, int(players)+1)]
shuffle(sequence1)
await ctx.send(sequence1)
sequence2 = [i for i in range(1, int(players)+1)]
shuffle(sequence2)
await ctx.send(sequence2)
sequence3 = [i for i in range(1, int(players) + 1)]
shuffle(sequence3)
await ctx.send(sequence3)
答案 0 :(得分:0)
使用列表理解功能,还可以通过在末尾创建单个组来处理不规则列表。
l = [1, 6, 5, 3, 4, 2]
n = 2
lst = [l[i:i + n] for i in range(0, len(l), n)]
for i in lst:
print(i)
[1, 6]
[5, 3]
[4, 2]
答案 1 :(得分:-1)
您可以直接导入random并使其随机化,这样可以节省大量的编码时间。如果您想做一个随机的主意,这就是代码,那么我会对其进行测试以确保它可以正常工作,因此不必担心。
import random
numbers = [1, 2, 3, 4, 5, 6]
random.shuffle(numbers)
print(numbers)