list

Published by onesixx on

T/F

a = [1,2,3]
b = [True, True, False]

[a[i] for i in range(len(a)) if b[i]]
# [1, 2]

특정 문자열을 포함한 원소 찾기

https://lapina.tistory.com/108

list comprehension 이 핵

fruit_list = ['딸기', '바나나', '블루베리', '블랙베리', 
    '오렌지', '사과', '스트로베리', '베리새끼', '오베리아나', '05베리']
find_berry = '베리'

rlt_word = [s for s in fruit_list if find_berry in s] 
# ['블루베리', '블랙베리', '스트로베리', '베리새끼', '오베리아나', '05베리']

rlt_idx = [i for i in range(len(fruit_list)) if find_berry in fruit_list[i]]
# [2, 3, 6, 7, 8, 9]

# fruit_list[rlt_idx] XXX
[fruit_list[i] for i in rlt_idx]

### Regular Expressions: Search in list : 베리가 마직막일때만
import re
#r = re.compile(".*베리$")   
r = re.compile(".*"+find_berry+"$")  
list(filter(r.match, fruit_list))
# ['블루베리', '블랙베리', '스트로베리', '05베리']

List 합집합, 교집합, 차집합, 대칭차

https://zetawiki.com/wiki/Python_리스트 합집합, 교집합, 차집합, 대칭차

L1 = ['A', 'B', 'C', 'D']
L2 = ['C', 'D', 'E', 'F']

# 합집합 
set(L1).union(L2)
set(L1)|set(L2)

# 교집합
set(L1).intersection(L2)
set(L1)&set(L2합

# 차집합
set(L1).difference(L2)
set(L1)-set(L2)

            
[ x for x in L1 if x not in L2]            
            
            
# 합집합-교집합
set(L1).symmetric_difference(L2)
set(L1)^set(L2)

리스트에 리스트를 리스트로 (2차원 리스트를 1차원 리스트로 변환, flatten)

https://codechacha.com/ko/python-flatten-list/

sum(iterable, [])은 []에 iterable의 모든데이터를 더하는 함수.
[] + ['2'] + ['25'] + ['78']의 연산을 수행하면서 결국 2차원에서 1차원 리스트로 변환

itertools.chain()는 인자로 전달되는 *arg
*arg는 *LL 이렇게 써도 되고, 몇개의 인수를 받을 지 모르지만, 받아서 처리하고, Tuple형태로 출력

LL = [['2'],
 ['25'],
 ['78']]

sum(LL, [])
# ['2', '25', '78']

import itertools
list(itertools.chain(*LL))

알파벳 예제 만들기

import string

Alist = list(string.ascii_lowercase)
# ['a', 'b', 'c', 'd', 'e', 'f', 'g', .... 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

list 나누기

import string
Alist = list(string.ascii_lowercase)
Blist = Alist[:10]
# ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

### 리스트를 크기 n의 리스트로 분할하기
n = 4
### way1
result = [ Blist[i*n : (i+1)*n] for i in range((len(Blist)+n-1)//n)]

### way2
def divideList(someList, n):
    return [someList[i: i+n] for i in range(0, len(someList), n)]

### way3 
def divideList(someList, n):
    for i in range(0, len(someList), n):
        yield someList[i: i+n]

list(divideList(Blist, n))
# [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j']]


### 리스트 d 개로 분할하기
d = 3

값 삽입

append() : 마지막에 데이터 v 추가

myList.append(‘v’)

list1 = [12, 23, 19]
list2 = [4, 6, 12, 19]

list1.append(list2)
# [12, 23, 19, [4, 6, 12, 19]]

list1.append('a') 
# [12, 23, 19, 'a']

insert() : i인덱스에 v추가

myList.insert(2, ‘v’)

list1 = [12, 23, 19]
list2 = [4, 6, 12, 19]

list1.insert(0, 'a')
print(list1)
# ['a', 12, 23, 19]

list2.insert(2, 'b')
print(list2)
# [4, 6, 'b', 12, 19]

list 합치기,확장 extend()

aList + bList

aList.extend(bList)

list1 = [12, 23, 19]
list2 = [4, 6, 12, 19]

list1 + list2 
# [12, 23, 19, 4, 6, 12, 19]

list1.extend(list2)

cf> list1.append(list2)
# [12, 23, 19, [4, 6, 12, 19]]

삭제

리스트.remove(a) 리스트에 있는 a 원소찾아 삭제

del 리스트[i] i인덱스에 있는 원소 삭제

리스트.pop(i) 리스트에 있는 i인덱스 꺼내서 Return하면서 버림

정렬 list.sort() vs. sorted(list)

<list>.sort() <list>.reverse()

None을 반환

원본 리스트 순서를 변화시킨다. (새로운 복사본을 만들지 않기 때문에 빠름)

sorted(<list>)

정렬된 새로운 리스트를 반환

찾기

‘a’ in myList : T/F 를 return

문자열 변경

sss= ['abc', 'def', 'ghj']
["bty_"+i for i in sss]
# ['bty_abc', 'bty_def', 'bty_ghj']

스트링.startswirh(“ss”) & 스트링.endswith(“.txt”)

[file for file in file_list if file.startswith(
    "m01_part") & file.endswith(".json")]
A = [ 'aa_std', 'bb_mean', 'cc']
B = [ 'aa', 'cc']
[ i for i in B if i  in A ]
[ i for i in B if i+'_std' in A]

Categories: Python Basic

onesixx

Blog Owner

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x