TIL - Python list,dict,reduce

kyoungyeon·2023년 8월 9일
0

TIL

목록 보기
86/110

Storm, Typhoon,Hurricane,Cyclone,Torando

Status

Real Typhoon is Coming

정말 바쁜 한 주가 지나고 !
그토록 원하던 취업을 이루었고, 좋아하던 일, 해보고 싶었던 업무를 하게 되서, 뿌듯하기도 한 한주인데.

방대한 보안 지식과 FireWall 설치속에서 아직은 태풍속에 휘말린 상황이다

SIEM , SOAR

  • Soar: Network, Cloud, SIEM 관리, Endpoint PlatForm 관리, 호스트와 Endpoint Operation Management

  • Siem :Network, Cloud, Endpoint 탐지 및 시각화

Python

set, list, dictionary (+tuple)

  • 자료구조에서 3대장인데, 문제 풀이에 한결같이 어렵게 느껴진다.

문제나 열심히 풀자..

  • Con1 : 2차원 리스트 1차원으로 변환
list1 = [[1,1],[1,2],[2,22],[3,16],[4,7]]
list2 = sum(list1,[])
print(list2)
import numpy as np
list1 = [[1,1],[1,2],[2,22],[3,16],[4,7]]
list2 = np.array(list1).flatten().tolist()
print(list2)
import itertools
list1 = [[1,1],[1,2],[2,22],[3,16],[4,7]]
list2 = list(itertools.chain.from_iterable(list1))
print(list2)
import numpy as np
list1 = [[1,1],[1,2],[2,22],[3,16],[4,7]]
list2 = np.concatenate(list1).tolist()
print(list2)
  • 여기서 tolist() 처리를 안하면
    <class 'numpy.ndarray'> 가 나오니 주의.
import numpy as np
list1 = [[1,1],[1,2],[2,22],[3,16],[4,7]]
list2 = np.array(list1).flatten().tolist()
print(list2)
from functools import reduce
import opertor
list1 = [[1,1],[1,2],[2,22],[3,16],[4,7]]
list2 = list(reduce(operator.add, list1))
print(list2)
  • JS
arr.reduce(callbackfunc(acc, curr,curIdx, array) { return acc + curr; }, initValue)

filter, map 과 함께 쓰이는 메소드로 알고 있었는데 좀 달라서 신선했다.

list1 = [[1,1],[1,2],[2,22],[3,16],[4,7]]
list2 = [x for inner_list in list1 for x in inner_list]
print(list2)

Output :

[1, 1, 1, 2, 2, 22, 3, 16, 4, 7]

python -list, dic,set

  • dictionary
    • key,value 활용도 높음
    • 순서없음!
    • 수정, 삭제(del,remove), 추가(add)
    • update, keys, items 등..
      • len의 경우 index와 다르므로 유의
  • 순서 보장 안됌
    • set 으로 중복 정리,tuple로 값을 고정, sorted를 통해 data 중복값만 오름차순 정리
 list(map(dict, set(tuple(sorted(d.item())) for d in data)))  
  • 순서보장
    collections.OrderedDict.fromkeys()
    python 3.7 ver 이상 dict.fromkeys()

    • 주어진 값들을 키 값으로 사용하는 딕셔너리(dictionary)를 반환한다.
    • value가 있다면 모든 키 값들에 대해 value로 값이 정해지며 없다면 None이 된다.
    • iterable에 추가된 원소들의 순서가 유지
 list(map(dict, collections.OrderedDict.fromkeys(tuple(sorted(d.item())) for d in data))) 
  # 3.7 ver
  list(map(dict, dict.fromkeys(tuple(sorted(d.items())) for d in data)))
  • list
    특정 key값 중복일 경우
    list({v['id']:v for v in data}.values())

dictionary- examples

  • 위 3개 메소드의 시간복잡도에 대한 글을 발견
    reference

Python - reduce 활용

  • 1 reduce
from functools import reduce
def sum(a,b):
	print(f"[a={a},b={b}] sum ={a}+{b} ={a+b}")
	return a+b
numbers = [1,2,3,4,5]
total = reduce(sum, numbers)
print(f"total ={total}")

재귀적으로 함수를 호출함

  • sum(1,2) call return 3
  • to sum(3,3) call return 6
  • to sum(6,4) call return 10
  • to sum(10,5) call return 15

output

total =15
  • reduce + lambda
from fuctools import reduce

numbers =[1,2,3,4,5]
total = reduce( lambda a,b : a+b, numbers)
print(f"total ={total}")

output

total =15

geekPython

ETC

Excercise

최근 이틀간 운동을 못 갔다.

아 운동 마렵다..

오늘 닭가슴살 먹으며 꼭 가겠다고 마음먹었는데
체력이 떨어진 것이 느껴진다

남아서 코드 좀 보다 보니,
마지막 타임에 늦어버려서 그냥 버리고 왔다 ...

내일은 태풍에 우산이 부러져도 간다.

profile
🏠TECH & GOSSIP

0개의 댓글