LoginSignup
0
0

More than 1 year has passed since last update.

pythonのlistに、先頭inseart、終端にinseart、classもinseartしてみた際の備忘メモ

Last updated at Posted at 2022-01-23

pythonのlistに、先頭inseart、終端にinseart、classもinseartしてみた際の備忘メモです。
(listはアクセスにO(N)の計算量が掛かるようなので、配列サイズが大きい場合はdeque等を使う事をおすすめします。ここではN=1000未満の大きさを扱うことを想定)

test_list.py
l=[]

### 先ずは先頭にinsertしてみる
l.insert(0, 1)
l.insert(0, 2)
l.insert(0, 3)

# print
print("--- print")
print(l)

# pop
print("--- pop")
print(l.pop(0))
print(l.pop(0))
print(l.pop(0))
print(l)
l.clear()


### 次に、終端にinsertしてみる
l.insert(len(l), 1)
l.insert(len(l), 2)
l.insert(len(l), 3)

# print
print("--- print")
print(l)
for i in range(len(l)):
    print(l[i])
l.clear()


### classをいれてみる
print("--- class")
class Point:
  def __init__(self, x, y):
    self._x = x
    self._y = y

  def output(self):
    print('Point(%d, %d)' % (self._x, self._y))

P1 = Point(1,1)
P2 = Point(2,2)
P3 = Point(3,3)
l.insert(len(l), P1)
l.insert(len(l), P2)
l.insert(len(l), P3)
print(l)

# popしてみる
PP1 = l.pop(0)
PP2 = l.pop(0)
PP3 = l.pop(0)
print(PP1._x, PP1._y)
print(PP2._x, PP2._y)
print(PP3._x, PP3._y)

実行する

python test_list.py
--- print
[3, 2, 1]
--- pop
3
2
1
[]
--- print
[1, 2, 3]
1
2
3
--- class
[<__main__.Point object at 0x10acfc278>, <__main__.Point object at 0x10acfc2e8>, <__main__.Point object at 0x10acfc320>]
1 1
2 2
3 3

参考

Pythonのデータが「deque」の使い方
dequeから範囲を指定して値を取得
Pythonで各要素にO(1)でランダムアクセスできるdeque(両端キュー)を書いてみた

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