0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】基礎の基礎 - 零ゼロ - ほぼ自分へのメモ

Last updated at Posted at 2025-07-16

指定文字列が他の文字列内に存在するかの判定

# in演算子で判定を行う方法
names = "sato ken mana mai syota"
print('mai' in names)
### True

#文字列の位置取得 - find() / rfind() / index() / rindex()
print(names.find('mana'))
### 9

#また、第2引数, 第3引数にstart, endを入れることでstart以降、endまでの範囲で検索が可能。
#rfind()は末尾から検索。
#index() / rindex()もfind() / rfind()同様にindexを返すが、もし、その文字列が存在しなかった際に、find() / rfind()は-1を返すのに対し、index() / rindex()はエラーになる。


#判定 + 位置取得 - re.search()
#最初の一つを検索して、返す。もし、全ての存在を返してほしい場合は、
#re.findall() -- 存在した文字そのものを返す
#re.finditer() -- 存在した位置を返す。 も使える。

#追加でその文字列がいくつ存在するかを見る。
print(names.count('ma'))
### 2

リストへの挿入

list_1 = [ 1, 2, 3 ]
list_2 = [ 101, 102, 103 ]

# リストの末尾に要素を追加: append()
list_1.append('a')
print(list_1)
### [1, 2, 3, 'a']

# リストとリストを結合(連結): extend()
list_1.extend(list_2)
print(list_1)
### [1, 2, 3, 101, 102, 103]

# リストの指定位置に要素を追加(挿入): insert([挿入するindex], [挿入する値])
list_1.insert(0, 301)
print(list_1)
### [301, 1, 2, 3]

# スライス リストに別のリストを指定位置に挿入
list_1[1:2] = [201, 202, 203]
print(list_1)
### [1, 201, 202, 203, 2, 3]

#リストをまとめてループ

keys = ["a", "b", "c"]
values = [2, 4, 7]
 
for (k, v) in zip(keys, values):
    print str(name) + ":" + str(age)

辞書型の扱い

dict = {"a":"Osaka", "b":"Fukui", "c":"Kyoto"}

print(dict.keys())
### dict_keys(['a', 'b', 'c'])

print(dict.values())
### dict_values(['Osaka', 'Fukui', 'Kyoto'])

print(dict.items())
### dict_items([('a', 'Osaka'), ('b', 'Fukui'), ('c', 'Kyoto')])

小数点の切り捨て / 切り上げ - math.floor() , ceil()

import math

print(math.floor(10.123))
# 10

print(math.floor(-10.123))
# -11

print(math.ceil(10.123))
# 11

print(math.ceil(-10.123))
# -10

.format() 演算以外での文字列への代入

substitute_0 = '代入'
substitute_1 = '文字'
substitute_2 = 'です'

print('a is {}'.format(substitute_0))
### a is 代入

print('b is {0} {1} {2}'.format(substitute_0, substitute_1, substitute_2))
### b is 代入 文字 です
#{}内のインデックスは.format()のインデックス。省略も可能。

.format()をf-stringsという別のやり方

x, y, z = a, b, c

print(f'a is {x}, {y}, {z}')
### a is a b c

関数 func

def func():
    return "返り値"

繰り返し

num = 3
for cand in range(num):
    print("この文がnum回繰り返す")

#inの後にはリストを入れることができる
#a = ["a", "b", "c", "d"]
# for cand in a: とか for cand in len(a)

continueとbreak

for i in range(1, 6):
    if i == 3:
        continue
    print(i, end = ",")
>>> 1,2,4,5,

for i in range(1, 6):
    if i == 3:
        break
    print(i, end = ",")
    
>>>> 1,2,

分岐

if a>=5:
    break #if文のサイクルから抜ける
    continue #if文の次のサイクルへ移る。

Pythonでの論理演算子(ブール演算子)

and # → Cなどでは &&
or # → Cなどでは ||

"3 6 0"のような入力値をそれぞれの値で分割 - .split()

x = "3 6 0"
y = x.split()
### "3", "6", "0"

# また、split(',')のようにすることで","ごとに分割することも可能

文字列を分割するリスト - list()

print('日月火水木金土'.split())
# ['日月火水木金土']

print(list('日月火水木金土'))
# ['日', '月', '火', '水', '木', '金', '土']

#値の中にある文字・文字列の出現回数をカウント

s = 'ambkdmflamvkflsmfa'
s.count('a', start, end)

二つの変数(同数)を一歩をkey,他方をvalueとして新たに辞書を作成

keys = ['1年生', '2年生', '3年生', '4年生']
values = ['たかし', 'つよし', 'あい', 'まい']
newDict = dict(zip(keys, values))

リストの長さを取得

a = len(["Red", "Green", "Blue"])
print(a)

### 3

変数の型変換

input_value = input()
### 100の場合
modeified_input_value = int(input_value)
print(modeified_input_value)

###100

###, が入る数字には注意
print(int('10,000'.replace(',', '')))
### 10000

# ちなみに、文字列に変換 str() / 少数字 float('1.23')

リストに値を追加

# 例: リストに新しいフルーツを追加
fruits = ['apple', 'banana', 'cherry']
fruits.append('orange')
print(fruits)  # ['apple', 'banana', 'cherry', 'orange']

辞書から特定のkeyを除外する

d = {'k1': 1, 'k2': 2, 'k3': 3}

removed_value = d.pop('k1')
print(d)
### {'k2': 2, 'k3': 3}
#.pop()の返り値はその削除したkeyまたはindexのvalue。

# .remove()はリストの値を宣言することでリスト内のその値を削除します。
fruits = ["apple", "banana", "cherry", "date"]
fruits.remove("banana")  # "banana" を削除
print(fruits)  # 出力: ['apple', 'cherry', 'date']

辞書やリストのコピー

#dict1を作ります。
dict1 = {"red":1, "blue":2, "yellow":3}
 
#dict2にdict1を代入します。
dict2 = dict1

#こっちなら、オリジナルとして新たにコピーできる
dict2 = dict1.copy()
 
#dict2の値を変更します。
dict2["red"] = 4

一見問題ないように見えますが、実は、このとき元の辞書(dict1)も変更されてしまっています。

特定の値がリストの何番目にあるのかを取得する - .index()

l = [30, 50, 10, 40, 20]

print(l.index(30))
# 0

ベクトル計算

特に、マスなどの移動課題などで現在地からの移動と移動位置などの算出するなどに使う。
行列や内積などの計算にも。

import numpy as np

x = np.array([1,2,3])
y = np.array([4,5,6])
x + y

特定の要素がリストに含まれているかを算出

print(1 in [0, 1, 2])
# True

print(100 in [0, 1, 2])
# False

辞書のキーの一覧を取得

# 辞書の作成
my_dict = {'a': 1, 'b': 2, 'c': 3}

# キーの一覧を取得
keys_view = my_dict.keys()

# キーの一覧を表示
print(keys_view)  # dict_keys(['a', 'b', 'c'])

# リストに変換
keys_list = list(my_dict.keys())
print(keys_list)  # ['a', 'b', 'c']
0
1
1

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?