LoginSignup
0
2

More than 5 years have passed since last update.

Pythonのデータ型の小さなメモ

Last updated at Posted at 2017-08-25

test.python
# cat test.py
# -*- coding: utf-8 -*-

num = 10
print(num)
print(type(num))
実行
10
<class 'int'>

文字列

test.python
n = "kure"
print(n)
print(type(n))
実行
kure
<class 'str'>

リスト

Cの配列と同じ。添字は整数値。データを[]で囲むかlist(データ)でリストデータを作る。可変長。

test.python
n = [1,2,3,4]
print(n)
print(type(n))

# 追加
print("追加")
n.append(5)
print(n)

# 挿入
print("挿入")
n.insert(2,'insert')
print(n)

# 削除
print("削除")
del n[0]
print(n)
実行
[1, 2, 3, 4]
<class 'list'>
追加
[1, 2, 3, 4, 5]
挿入
[1, 2, 'insert', 3, 4, 5]
削除
[2, 'insert', 3, 4, 5]

for

test.py
n = [1,2,3,4]
for v in n:
        print(v)
実行
1
2
3
4

タプル

変更不可なリスト。データを()で囲むかtuple(データ)でタプルデータを作る。
ただし、空タプルは()。要素が一つのデータは(データ,)と最後にカンマを書く。カンマを書かないと単なる算術優先演算の括弧として扱われてしまう。
なお、カンマがあればタプルになり、()は書かなくてもよい。ただし、カンマの適用対象が不明確な場合は()で囲まなければならない。

test.python
n = (1,2,3)
print(type(n))
print(n)
実行
<class 'tuple'>
(1, 2, 3)

ディクショナリ

連想配列。リストは整数値が要素、ディクショナリはキーが要素。キーは数値、文字列、タプル、が指定可能。
{} で囲むデータは、キー:値 という形で指定します。
{} で囲む以外にも dict(データ) でも作れます。
dict() は、キーと値のペアのシーケンス、あるいは変数名=値でデータを指定します。

test.python
n = {'a':1, 'b':2, 'c': 3}
#for文
for v in n:
        print(v)

for k, v in n.items():
        print(k, v)
実行
a
b
c
a 1
b 2
c 3
0
2
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
2