[Python]list의 다양한 예제

리스트 쪼개기

# List slicing : L[start:stop:step]
x = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"]

print(x[4:7])
print(x[4:7:1])
print(x[-9:-6])
print(x[4:-6])
print(x[-9:7])
print(list(x)[4:7])

print(x[6:3:-1])
print(list(reversed(x[6:3:-1])))

## 결과
['e', 'f', 'g']
['e', 'f', 'g']
['e', 'f', 'g']
['e', 'f', 'g']
['e', 'f', 'g']
['e', 'f', 'g']
['g', 'f', 'e']
['e', 'f', 'g']

리스트에서 선택(필터링)

x = ["grapes", "mango", "orange", "peach", "apple", "lime", "banana", "cherry", "tomato", "kiwi", "blueberry", "watermelon"]

print(list(map(lambda t: t.upper(), filter(lambda y: y in ["apple", "kiwi"] ,x))))

result = []
for c in x:    
    if (c in ['apple', 'kiwi']):
        result.append(c.upper())
print(result)    


result2 = []
for i in range(len(x)):
    if x[i] == 'apple' or x[i] == 'kiwi':
        result2.append(x[i].upper())
        
print(f'{result2}')


# 많이 사용하는 문법 : for 와 if문을 하나의 구문으로 생성
result3 = [a.upper() for a in x if a == 'apple' or a == 'kiwi']
print(result3)

## 결과
['APPLE', 'KIWI']
['APPLE', 'KIWI']
['APPLE', 'KIWI']
['APPLE', 'KIWI']

You may also like...

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다