0
0

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 1 year has passed since last update.

Python リストのある要素だけ除去したいとき

Last updated at Posted at 2022-02-25

要素1つ

方法1. itertoolsのchainで範囲を指定する
方法2. listのpopメソッド

import itertools

# 5番目の要素を取り除きたい
ls = [0,1,2,3,4,5,6,7,8,9,10]

# generater
genr = itertools.chain(range(0,5),range(6,11))
print('generater: ', [ls[i] for i in genr])

# pop
ls.pop(5)
print('pop: ', ls)
generater:  [0, 1, 2, 3, 4, 6, 7, 8, 9, 10]
pop:  [0, 1, 2, 3, 4, 6, 7, 8, 9, 10]

複数要素

方法1. itertoolsのchainで範囲を指定する
方法2. sortedのreverse & listのpopメソッド or delメソッド

import itertools

# 5番目と8番目の要素(5と8)を取り除きたい
ls = [0,1,2,3,4,5,6,7,8,9,10]

# generater
genr = itertools.chain(range(0,5),range(6,8), range(9,11))
print('generater: ', [ls[i] for i in genr])

# pop or del
# 普通に削除すると、次に削除する要素位置を-1する必要がある
# 直感的に削除するためには、
# 削除したい要素を降順にソートすることで実現できる
for i in sorted([5,8], reverse=True):
    ls.pop(i)
    # del でも結果は同じ
    # del ls[i]
print('pop(del): ', ls)
generater:  [0, 1, 2, 3, 4, 6, 7, 9, 10]
pop(del):  [0, 1, 2, 3, 4, 6, 7, 9, 10]
0
0
2

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?