【发布时间】:2023-01-21 05:09:38
【问题描述】:
我想以类似马拉松的形式独立地迭代列表的元素,这样每个车道/元素都可以随机/变化的速度移动。
为了仍然能够通过索引访问每个元素,我尝试了以下代码:
cyclists = ['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy'] #each elements represent an athlete
choose_athlete = random.choices((range(len(cyclists))), k=len(cyclists)) # index select athlete from elements/lane
################################################################
def circular_shifts(runners, step=1):
step %= min(len(e) for e in runners)
return [e[step:] + e[:step] for e in runners]
for laps in range(10):
for i in range(len(cyclists)):
cycling = circular_shifts(cyclists, i)
print(cycling)
#问题:::
#有没有一种方法可以在每个元素循环时将time.sleep 的概念应用到它们,这样我就可以确定它们的运行速度,即 lane1/element[0] 循环快,而 lane2 慢,等等?
另一个例子:
cyclists = ['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy'] #each elements represent an athlete
for i in range(5):
for aa in cyclists[0]:
time.sleep(0)
print(aa)
for bb in cyclists[1]:
time.sleep(0.1)
print(bb)
for cc in cyclists[1]:
time.sleep(0.2)
print(cc)
for dd in cyclists[1]:
time.sleep(0.3)
print(dd)
for ee in cyclists[0]:
time.sleep(0.4)
print(ee)
但是这种方法是单独打印的,相反,我希望输出仍然一起显示为列表,这样我就可以使用索引 ([0:4]) 访问它们
首选输出:
['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy']
['bcdea', 'ghijf', 'lmnok', 'qrstp', 'vwxyu']
['cdeab', 'hijfg', 'mnokl', 'rstpq', 'wxyuv']
['deabc', 'ijfgh', 'noklm', 'stpqr', 'xyuvw']
['eabcd', 'jfghi', 'oklmn', 'tpqrs', 'yuvwx']
['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy']
['bcdea', 'ghijf', 'lmnok', 'qrstp', 'vwxyu']
['cdeab', 'hijfg', 'mnokl', 'rstpq', 'wxyuv']
['deabc', 'ijfgh', 'noklm', 'stpqr', 'xyuvw']
['eabcd', 'jfghi', 'oklmn', 'tpqrs', 'yuvwx']
【问题讨论】:
-
我很不清楚你想用你的代码完成什么,以及当前代码的哪一部分“不起作用”。对于每个跑步者,他们都分配了一定的速度?那么你想确定哪个跑步者先到达终点?你想使用
time.sleep是因为你想以某种方式在打印输出中说明这一点吗? -
当前代码实际上可以工作,但我只需要添加 time.sleep 或任何其他方法,以便每个元素以不同的速度迭代。例如,如果 list[0] 需要 time.sleep(0.001),list[1] 在 time.sleep(0.002) 等时移动
-
你想要达到的目标有点不清楚。如果你想通过添加 time.sleep 来减慢 for 循环,就这样做吧。问题是什么,你想达到什么目的,你尝试了什么?
-
为什么不计算每个运动员在每次迭代中的行进距离。因此,如果每次迭代表示 5 分钟,以 5 分钟/公里的速度跑步的运动员将在迭代 1 中跑 1 公里,在迭代 2 中跑 2 公里等。更快的跑步者将根据他们的配速跑更多的距离,同样较慢的跑步者将有覆盖的距离更短。
-
听起来不错。关于那个的任何指针
标签: python