我想得到以下输出:
T1: j2
T2: j4
T3: j3
T1: j7
T2: j
T3: j6
T1: j5
我已经用for循环尝试过了,但是我做不到。这是我的代码:
import random
team = ['t1','t2','t3']
task = ["j","j2","j3","j4","j5","j6","j7"]
print (task)
s_task = random.sample(task,len(task))
print (s_task)
for itm in team:
for itm1 in s_task:
print(itm,itm1)
T1: j2
T2: j4
T3: j3
T1: j7
T2: j
T3: j6
T1: j5
答案 0 :(得分:2)
您似乎需要itertools.cycle
和random.choice
例如:
import random
from itertools import cycle
team = ['t1','t2','t3']
task = ["j","j2","j3","j4","j5","j6","j7"]
team = cycle(team)
for _ in range(len(task)):
print("{}: {}".format(next(team), random.choice(task)))
输出:
t1: j5
t2: j5
t3: j
t1: j7
t2: j6
t3: j7
t1: j3
答案 1 :(得分:1)
如果仅需要格式化输出的方式,则可以使用:
Formatted string literal又称f字符串(适用于Python 3.6或更高版本)
for itm in team:
for itm1 in s_task:
print(f"{itm}: {itm1}")
详细了解f字符串here。
如果您的Python3低于Python3.6,请坚持使用str.format()
并使用
print("{}: {}".format(itm, itm1))
答案 2 :(得分:0)
您可以使用string.format():
import random
team = ['t1','t2','t3']
task = ["j","j2","j3","j4","j5","j6","j7"]
print (task)
s_task = random.sample(task,len(task))
print (s_task)
for itm in team:
for itm1 in s_task:
print("{}: {}".format(itm,itm1))
这应该以您所需的格式打印
答案 3 :(得分:0)
使用串联,
print(itm, ": ", itm1)
使用旧字符串格式,
print("%s: %s"%(itm, itm1))
使用新的字符串格式,
print("{0}: {1}".format(itm, itm1))
import random
team = ['t1','t2','t3']
task = ["j","j2","j3","j4","j5","j6","j7"]
print (task)
s_task = random.sample(task,len(task))
print (s_task)
for itm in team:
for itm1 in s_task:
print(itm, ": ", itm1)
T1: j2
T2: j4
T3: j3
T1: j7
T2: j
T3: j6
T1: j5