簡體   English   中英

如何在以原始順序使用元素時訪問列表中的所有其他元素?

[英]How do I access every other element in a list while using the elements in the original order?

很抱歉這個令人困惑的問題。 我有一個名為 switch 的列表,其中包含 10 到 30 之間隨機選擇的數字。我試圖在以下 function 中使用這些數字(這只是開始):

def rewardfunc(y, switch):
   left_reward = []
   right_reward = []
   for x in range(switch[0]):
      left_reward.append(prob(y))
      right_reward.append(prob(1-y))
   for x in range(switch[1]):
      left_reward.append(prob(1-y))
      right_reward.append(prob(y))
   for x in range(switch[2]):
      left_reward.append(prob(y))
      right_reward.append(prob(1-y))
   for x in range(switch[3]):
      left_reward.append(prob(1-y))
      right_reward.append(prob(y))

在這個 function 中,switch 中的每個數字都用於定義一個試驗塊,但每個其他數字都定義一個不同的類型塊。 所以,我的問題是如何按順序使用 switch 中的每個數字,而將每個其他數字用於不同的任務? 目前,我把它寫成 x in range((switch[0]))... 有沒有辦法以更短的形式做到這一點?

希望我的問題有意義。 感謝您的任何幫助。

for i, x in enumerate(switch):
    for _ in range(x):
        if i % 2 == 0:
            left_reward.append(prob(y))
            right_reward.append(prob(1-y))
        else: 
            left_reward.append(prob(1-y))
            right_reward.append(prob(y))

在每次迭代中,只需交換對left_rewardright_reward的引用。 就像是

def rewardfunc(y, switch):
   l = left_reward = []
   r = right_reward = []
   for x1 in switch:
       for x2 in x1:
           l.append(prob(y))
           r.append(prob(1-y))
       l, r = r, l

如果你是理解的粉絲:

left_reward = [prob(1-y if i % 2 else y) for i in range(len(switch))]
right_reward = [prob(y if i % 2 else 1-y) for i in range(len(switch))]

如果prob(e)很昂貴,那么考慮預先計算:

prob_y, prob_inv_y = prob(y), prob(1-y)
left_reward = [prob_inv_y if i % 2 else prob_y for i in range(len(switch))]
right_reward = [prob_y if i % 2 else prob_inv_y for i in range(len(switch))]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM