0
3

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.

Python リスト要素を複数のインデックス(何番目か)で取得 シンプルな方法

Posted at

Pythonのリストから複数のリストを取り出す時、連続している場合はスライスで簡単に取り出せますが、ランダムな場合の方法がなかなか見つからなかったので記事にします。

###環境
Python 3.7.3

タプルで指定

list = ['banana', 'apple', 'lemon', 'grape', 'kiwi']
[list[i] for i in (1,4)]  #['apple', 'kiwi']

もしくはリストで指定

list = ['banana', 'apple', 'lemon', 'grape', 'kiwi']
list2=[2,3]
[list[i] for i in list2] #['lemon', 'grape']

Numpyなどのモジュールを利用する記事はあったのですが、シンプルに記述できました!

この英語のサイトを参照しました

0
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?