wiki:Python/Snippet/データ操作

Version 2 (modified by nakiki, 13 years ago) (diff)

--

データ操作

タプル

a = (1, 2, 3)
a1, a2, a3 = a
print a1
print a2
print a3

リスト

list = [1, 2, 3, 4, 5, 6, 7]
for item in list:
  if item % 3 == 0:
    list.remove(item)
print list
  • 課題:リストのサイズが大きくなった場合削除に時間がかかるか?

リストに含まれるか

list = [1, 2, 3, 4, 5, 6, 7]
x = 5
if x in list:
  print '%d exists' % x

list = [[1, 2], [3, 4], [5, 6]]
x = [3, 4]
if x in list:
  print '[%d, %d] exists' % (x[0], x[1])

タプルに含まれるか

x = 3
list2 = (1, 2, 3, 4, 5, 6, 7)
if x in list:
  print '%d exists' % x

x = (3, 4)
list3 = ((1, 2), (3, 4), (5, 6))
if x in list3:
  print '(%d, %d) exists' % x

繰り返し動作

def catstr(x, y):
  return x + y
seq1 = ['a', 'b', 'c']
seq2 = ['1', '2', '3']
print map(catstr, seq1, seq2)

辞書の表示

a = {'k1':100, 'k2':101, 'k3':102}
for k in a:
  print k, a[k]