0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

2次元リストで、各行のトップ3の値のインデックスを取得

Last updated at Posted at 2020-12-14

重複がない前提のコードです。

仕事で使おうと思ったけど、重複があるとダメなので

list_2d = [
    [1, 3, 5, 2, 4],
    [2, 4, 5, 3, 1],
    [6, 7, 8, 9, 2],
    [4, 8, 2, 6, 1],
    [7, 2, 9, 4, 5],
    [7, 9, 8, 5, 3],
    [4, 7, 2, 1, 3],
    [9, 3, 6, 5, 8],
    [0, 3, 7, 8, 2],
    [3, 7, 2, 5, 6]
    ]
    
# 並べ替える(大きい順)
ordered_list = [sorted(l, reverse=True) for l in list_2d]
print('ordered_list = \n', ordered_list, '\n')

# 左から3番目までを抜き出す(ベスト3が残る)
ordered3 = [l[:3] for l in ordered_list]
print('ordered3 = \n', ordered3, '\n')

# 各行における1位、2位、3位のインデックスを取得
# (先ほどのベスト3のリストの値をキーに、元のリスト内のインデックスを取得)
first_indexes = []
second_indexes = []
third_indexes = []
for i in range(len(list_2d)):
    first_indexes.append(list_2d[i].index(ordered3[i][0]))
    second_indexes.append(list_2d[i].index(ordered3[i][1]))
    third_indexes.append(list_2d[i].index(ordered3[i][2]))

print('1位のインデックス: ', first_indexes)
# 1位のインデックス:  [2, 2, 3, 1, 2, 1, 1, 0, 3, 1]
print('2位のインデックス: ', second_indexes)
# 2位のインデックス:  [4, 1, 2, 3, 0, 2, 0, 4, 2, 4]
print('3位のインデックス: ', third_indexes)
# 3位のインデックス:  [1, 3, 1, 0, 4, 0, 4, 2, 1, 3]
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?