【问题标题】:Applying time.sleep on each element of a python list对 python 列表的每个元素应用 time.sleep
【发布时间】: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


【解决方案1】:

这种设置方式对我来说有点太混乱了,所以我使用time.sleep 编写了我自己的比赛如何发生的版本。我试图添加很多 cmets 来解释所有步骤:

import time

runners = [
    {'name':'Samantha', 'speed':3.5, 'distance_traveled':0},
    {'name':'Ben',      'speed':2.9, 'distance_traveled':0}, 
    {'name':'Luis',     'speed':1.8, 'distance_traveled':0}, 
    {'name':'Jane',     'speed':2.2, 'distance_traveled':0}
    ] 
# each elements represent an athlete. Their name and their speed. Also 'distance traveled' tracker
# let's set the speed to be units (m/s). The distance traveled is measured in (m)

# initialize a "finish line" which registers when the distance traveled is enough to win
finish_line = 30    # Distance required to win.             Units of (m)
time_tracker = 0    # Total time elapsed.                   Units of (s)
time_delta = 1      # Change in time for each iteration.    Units of (s)

# fun printing stuff
print("And we're off! Here's the standings: ")

# "while some of the athletes have not finished yet"
while any(i['distance_traveled'] < finish_line for i in runners):
    # we can use time.sleep with a while loop to register the race for each second.

    # update the distance traveled for each runner
    for r in runners:
        r["distance_traveled"] += r["speed"]*time_delta
    
    # sort the runners dict depending on who's in first place, etc.
    runners = sorted(runners, key=lambda d: d['distance_traveled'], reverse=True) 

    print(f"
At time {time_tracker}s the current standings are:")
    for place, r in enumerate(runners):
        print(f'{place+1}.: {r["name"]} at {r["distance_traveled"]:.1f}m')
    
    time_tracker += time_delta
    time.sleep(time_delta)

还有很多我没有添加的东西,例如:

  1. 跑步者跑步时改变速度。随机决定速度?
  2. 当他们越过终点线时宣布获胜者。
  3. 其他环境因素,例如风或条件?

    希望这有帮助!玩得开心!

【讨论】:

    猜你喜欢
    • 2014-06-09
    • 1970-01-01
    • 2010-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多