# Python Array 追加削除結合

メソッド 説明
array.append(x) 末尾に追加
array.count(x) 指定要素が配列含む回数
array.remove(x) 指定要素を配列から削除
array.reverse() 配列順番逆転
array.tolist() 配列をリストに変換
array.insert(index, x) 配列 index の前に挿入

配列 for 文

row = 5
for i in range(row):
    for j in range(row+i):
        if(j < row - i - 1):
            print(' ', end='')
        else:
            print('*', end='')
    print()

#    *
#   ***
#  *****
# *******
#*********

配列基本操作

numbers = [1,2,3]
numbers += [4,5,6]      # 配列追加

print(numbers[1:3])     # [2, 3]

print(numbers[:])       # [1, 2, 3, 4, 5, 6]

print(numbers[-3:-1])   # [4, 5]

print(numbers[::-1])    # [6, 5, 4, 3, 2, 1]

list1 = ['a','b','c','d','e']
list2 = sorted(list1)
list3 = sorted(list1, reverse=True)
list4 = sorted(list1, key=len)

print(list1)    # ['a', 'b', 'c', 'd', 'e']
print(list2)    # ['a', 'b', 'c', 'd', 'e']
print(list3)    # ['e', 'd', 'c', 'b', 'a']
print(list4)    # ['a', 'b', 'c', 'd', 'e']

list1.sort(reverse=True)
print(list1)    # ['e', 'd', 'c', 'b', 'a']

Python で流れる文字アニメーション作成できる

import os
import time

def main():
    content = 'Pythonで流れ文字作れる~~~'
    while True:
        os.system('cls')     # os.system('clear')
        print(content)
        time.sleep(0.2)
        content = content[1:] + content[0]

if __name__ == '__main__':
    main()

# オブジェクト & 連想配列 加工処理

fruits = {
    'apple': 100,

    'orange': 50,
    'strawberry': 90,
    'avocado': 200,
    'raspberry': 240,
    'grapefruit': 110,
    'coconut': 500,
    'cherry': 1000,
    'pineapple': 300,
    'banana': 120,
    'durian': 2000,
    'peach': 120,
}

# 500円以上集合
fruits2 = {key: value for key, value in fruits.items() if value > 500}

print(fruits2)  # {'cherry': 1000, 'durian': 2000}

fruits = ['apple', 'orange', 'banana']
level = ['普通', '高級']

prices = [[None] * len(level) for _ in range(len(fruits))]

print(prices)

# [[None, None], [None, None], [None, None]]

配列ソート

def quick_sort(items, comp=lambda x, y: x <= y):
    items = list(items)[:]
    _quick_sort(items, 0, len(items) - 1, comp)
    return items


def _quick_sort(items, start, end, comp):
    if start < end:
        pos = _partition(items, start, end, comp)
        _quick_sort(items, start, pos - 1, comp)
        _quick_sort(items, pos + 1, end, comp)


def _partition(items, start, end, comp):
    pivot = items[end]
    i = start - 1
    for j in range(start, end):
        if comp(items[j], pivot):
            i += 1
            items[i], items[j] = items[j], items[i]
    items[i + 1], items[end] = items[end], items[i + 1]
    return i + 1

配列 map filter

items1 = list(map(lambda x: x ** 2, filter(lambda x: x % 2, range(1, 10))))
items2 = [x ** 2 for x in range(1, 10) if x % 2]
2021-01-22
  • python