Skip to content

Instantly share code, notes, and snippets.

@ishikota
Last active June 6, 2016 13:57
Show Gist options
  • Save ishikota/6016bdf0aaa0cd483b187ffc1d851aa9 to your computer and use it in GitHub Desktop.
Save ishikota/6016bdf0aaa0cd483b187ffc1d851aa9 to your computer and use it in GitHub Desktop.
listをi番目が先頭になるように並び替えたい

ex.

  • lst = [A,B,C], i=0 => ans = [A,B,C]
  • lst = [A,B,C], i=1 => ans = [B,C,A]
  • lst = [A,B,C], i=2 => ans = [C,A,B]

sorted(lst, key=lambda e: i-lst.index(e))みたいにして,iに近い程前に来るみたいにしたかったけど,
iより前にある値の評価が負になって上手く並び替えられなかった.
=> [lst[(i+j)%len(lst)] for j in range(len(lst))] で実装することにした.

以下実装をきれいにできないものか...

問題

p1.action_histories = [A,B]
p2.action_histories = [C]
p3.action_histories = [E,F]
playerの順番 : p3 => p1 => p2
求めるもの : all_action_histories = [E,A,C,F,B]

  def __order_histories(self, start_pos, players):
    ordered_players = [players[(start_pos+i)%len(players)] for i in range(len(players))]
    all_player_histories = [p.action_histories for p in ordered_players]
    max_len = max([len(h) for h in all_player_histories])
    unified_histories = [self.__unify_length(max_len, l) for l in all_player_histories]
    ordered_histories = reduce(lambda acc, zp: acc + list(zp), zip(*unified_histories), [])
    return [history for history in ordered_histories if not history is None]
    
  def __unify_length(self, max_len, lst):
    for _ in range(max_len-len(lst)):
      lst.append(None)
    return lst
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment