별의별 이야기

List 본문

3./Python

List

Hailey Han 2024. 12. 31. 02:03
728x90

List 개요

animal=['rabbit', 'dog', 'tiger', 'lion', 'snake']
a= 'lion'
if a in animal: 
    print(a, 'is in animal')
else: 
    print(a, 'is not in animal')

list에서 in operator

cheeses = ['Cheddar', 'Edam', 'Gouda']
if 'Edam' in cheeses: #list에 'Edam'이 있으면 true를 실행함 
    print(True)
for food in cheeses: #리스트 cheeses의 각 요소를 반복하면서 출력
    print(food)

list에서 len() operator

animal=['rabbit', 'dog', 'tiger', 'lion', 'snake']
for i in range(len(animal)-1):  # 리스트 animal의 길이에서 1을 뺀 범위만큼 반복
    print(animal[i])  # 리스트 animal의 현재 인덱스 i에 해당하는 요소를 출력
cheeses = ['Cheddar', 'Edam', 'Gouda'] 
numbers = [1, 3, 5, 7, 9, 11]

for cheese in cheeses :  #cheeses요소 빼오기 
    print(cheese) #cheeses 하나씩 프린트

for i in range(len(numbers)) : #number를 요소의 개수로 반환함. 
    numbers[i] = numbers[i] * 2 #number가 하나씩 받아질 때 2를 곱함. 
    print(numbers[i]) #2곱한 값으로 출력됨 

print(numbers) #이거는 그냥 number가 세로로 나오는게 아니라 리스트로 하나가 나옴.

 

list slice

t = ['a', 'b', 'c', 'd', 'e', 'f']
print(t[1:3]) 
print(t[:4])
print(t[3:])

연습문제1
1. word = '', tempword='' 가 아닌 word=[], tempword=[] 로 변경해야 함.
2. word = [tempword]+[word] 가 아니라 = word + tempword로 변경. 굳이 또 []를 안적어도 되고, 순서도 새로운게 오른쪽으로 가게 하려면 순서를 바꿔야 함. 

num = int(input('item을 입력하세요: '))
word = []
tempword=[]

for i in range(num): 
    print(i, '번째')
    t = input('추가할 element 입력: ')
    tempword = [t]
    word = word + tempword
print(word)

연습문제2 
문제: 리스트를 읽으면서 각 아이템에 모음이 몇 개 있는지 센 후 출력
내 문제점: 리스트로 읽혀서 바로 j in 'aeiou'로 하면 False 가 계속 출력 됨. 모음 세는 로직이 없음. 또한 tempanimal = [i] 가 리스트를 덮어씀. 이 말은 반복문 안에 새 리스트 [i]로 계속 초기화 되고, 기존 내용을 덮어쓰게 됨. 즉 마지막 입력 단어만 포함하며, 이전 데이터를 잃어버림.. 즉 제대로된 결과 출력 불가. 

#답
animal=['Rabbit', 'lion', 'snake', 'cabbage', 'Apple', 'banana'] 
for i in animal: 
    count=0
    for j in i: 
        if j in 'AEIOUaeiou':
            count +=1 
        print (i, '모음수',count)
#답2 
animal=['Rabbit', 'lion', 'snake', 'cabbage', 'Apple', 'banana'] 
for i in animal:    # animal 리스트의 각 단어를 순회
    tempanimal = [] # 각 단어의 모음을 저장할 임시 리스트 초기화
    for j in i:     # 단어의 각 문자를 하나씩 순회
        if j in 'AEIOUaeiou':     # 문자가 모음인지 확인
            tempanimal.append(j)  # 모음을 tempanimal에 추가
    print(f"{i} 모음 수: {len(tempanimal)} 개, 모음: {tempanimal}")

List methods 이해

sort와 sorted

sort: list를 그 자리에서 정렬, 인덱스를 변경하고 none 반환
sorted: 새로운 정렬된 목록을 반환하며, 원래 목록은 영향을 받지 않음

method 활용하기

연습문제1

자신의 이름을 입력 받아서 리스트로 만들어서 출력한다.
이름은 문자 중 삭제할 문자를 입력 받아 그 문자를 생성된 리스트에서 삭제한다. 
삭제된 후 리스트의 내용을 출력한다.

name=input('enter name: ')
delchr=input('삭제 문자: ')
nameList=list(name) 
print('초기 리스트:',nameList)

i=0 #반복할 변수 
while i<len(nameList): #리스트 길이만큼 반복
    if nameList[i] == delchr: #현재 인덱스 요소가 삭제 대상 문자와 같다면
        nameList.remove(delchr) #해당 문자를 리스트에서 제거 
    else: 
        i+=1 #문제없으면 인덱스를 증가
print('최종 리스트:',nameList)

연습문제2

1. 원하는 단어 입력받기
3. 입력 받은 단어를 구성하는 알파벳 순서대로 정렬
2. 모든 알파벳은 소문자로 바꾸어 정렬
4. 공백이 있는 경우 삭제

name=input('enter string: ')
name = name.lower() #소문자
nameList = list(name)

for ch in nameList:
    if ch.isspace(): 
        nameList.remove(ch)
nameList.sort()
print(nameList) 
#index로 리스트를 탐색하는 문제가 아님. 공백이면 지워라의 반복. 
#인덱스 단위로 리스트를 찾으며 코드를 변경하는 문제

## sort먼저 한 경우 ?? 
name=input('enter string: ')
name = name.lower() #소문자
nameList = list(name)
nameList.sort()
for i in range(0, len(nameList)):
    if nameList[i].isspace():
        nameList.remove('')
        i-=1
        if i < 0: 
            i=0 
        
print(nameList)