๐ŸŒCoding/๐ŸŒŸPython3

[Python] list

๋ฟŒ์•ผ._. 2021. 2. 9. 22:12

Python3์˜ list์— ๊ด€ํ•ด ๋„์ ๋„์ โœ ํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

 

1) list

 

 โ‘  list ์„ ์–ธ

x=[] #list ์„ ์–ธ

 ๋ฆฌ์ŠคํŠธ ์„ ์–ธ ๋ฐฉ๋ฒ•์ž…๋‹ˆ๋‹ค. ์•„์ฃผ ๊ฐ„๋‹จ!!

 

x=[i for i in range(5)] #[0, 1, 2, 3, 4]

  ๋ฐ˜๋ณต๋ฌธ ์‚ฌ์šฉํ•˜์—ฌ ๋ฆฌ์ŠคํŠธ ์„ ์–ธํ•˜๋Š” ๋ฐฉ๋ฒ•์ž…๋‹ˆ๋‹ค.

 

 

 

 โ‘ก list ์›์†Œ ์ถ”๊ฐ€

x.append(5) #list ์›์†Œ ์ถ”๊ฐ€

 append๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ฆฌ์ŠคํŠธ์— ์›์†Œ๋ฅผ ์ถ”๊ฐ€ํ•˜๋Š” ๋ฐฉ๋ฒ•์ž…๋‹ˆ๋‹ค. 

 

x.insert(1,"hi") #['a', 'hi', 'b', 'c', 'd']

 insert(์›์†Œ ์ถ”๊ฐ€ํ•  index, ์ถ”๊ฐ€ํ•  ์›์†Œ ๊ฐ’)

 

 

 

 โ‘ข list ์›์†Œ ์‚ญ์ œ

 

 ๋ฆฌ์ŠคํŠธ ์›์†Œ๋ฅผ ์‚ญ์ œํ•˜๋Š” ๋ฐฉ๋ฒ•์—๋Š” ์—ฌ๋Ÿฌ ๊ฐ€์ง€๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. ์ดํ•ดํ•˜๊ธฐ ์‰ฝ๊ฒŒ ํ•˜๊ธฐ ์œ„ํ•˜์—ฌ ์˜ˆ๋ฅผ ๋“ค์–ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹น

 

 ex) x=["a", "b", "c", "d"]

del x[2] #['a', 'b', 'd']

 del list๋ช…[index]์„ ์‚ฌ์šฉํ•˜์—ฌ ๋ฆฌ์ŠคํŠธ ์›์†Œ๋ฅผ ์ œ๊ฑฐํ•˜๋Š” ๋ฐฉ๋ฒ•์ž…๋‹ˆ๋‹ค.

 

x.remove("b") #['a', 'c', 'd']

 list๋ช…. remove(์ œ๊ฑฐํ•  ๊ฐ’)์„ ์‚ฌ์šฉํ•˜์—ฌ ๋ฆฌ์ŠคํŠธ ์›์†Œ๋ฅผ ์ œ๊ฑฐํ•˜๋Š” ๋ฐฉ๋ฒ•์ž…๋‹ˆ๋‹ค.

 

x.pop(2) #['a', 'b', 'd']

 list๋ช…. pop(index)์„ ์‚ฌ์šฉํ•˜์—ฌ ๋ฆฌ์ŠคํŠธ ์›์†Œ๋ฅผ ์ œ๊ฑฐํ•˜๋Š” ๋ฐฉ๋ฒ•์ž…๋‹ˆ๋‹ค.

 

 

 

 โ‘ฃ list slice

 

 ex) x=["a", "b", "c", "d"]

x= x[1:] #['b', 'c', 'd']
x= x[:3] #[a', 'b', 'c']
x= x[1:3] #['b', 'c']

 ๋ฆฌ์ŠคํŠธ๋ฅผ ์Šฌ๋ผ์ด์‹ฑํ•˜๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ๋Š” list๋ช…[์Šฌ๋ผ์ด์‹ฑ ์‹œ์ž‘ํ•  index: ์Šฌ๋ผ์ด์‹ฑ ๋๋‚ผ index+1]

 

 

 

 โ‘ค list ๊ธธ์ด, index ์ฐพ๊ธฐ, count

 

 ex) x=["a", "b", "c", "d"]

len(x) #4

 len์„ ์‚ฌ์šฉํ•˜์—ฌ list ๊ธธ์ด ๊ตฌํ•˜๊ธฐ

 

x.index("b") #1

 index๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ฐพ๋Š” ๊ฐ’์˜ ์œ„์น˜ ๋ฐ˜ํ™˜

 

 

 ex) x=["a", "b", "c", "d", "a"]

x.count("a") #2

 count(์ฐพ๋Š” ๊ฐ’)์„ ์‚ฌ์šฉํ•˜์—ฌ ์ฐพ๋Š” ๊ฐ’์˜ ๊ฐœ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜

 

 

 

 โ‘ฅ list ์ •๋ ฌ, ๋’ค์ง‘๊ธฐ

 

 ex) x=["b", "d", "a", "c"]

x.sort() #['a', 'b', 'c', 'd']

 

 ex) x=["a", "b", "c", "d"]

x.reverse() #['d', 'c', 'b', 'a']

 

 

โ‘ฆ list to ๋ฌธ์ž์—ด

temp=['a','b','c']

print(''.join(temp)) #abc

 

'๐ŸŒCoding > ๐ŸŒŸPython3' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Python] lambda  (0) 2021.07.29
[Python] ์ˆœ์—ด, ์กฐํ•ฉ  (0) 2021.05.16
[Python] ๋”•์…”๋„ˆ๋ฆฌ  (0) 2021.05.02
[๊ฐ€์ƒํ™˜๊ฒฝ] ํŒŒ์ด์ฌ ํ™˜๊ฒฝ์„ค์ •  (0) 2021.03.13
[Python] ์ž…์ถœ๋ ฅ  (0) 2021.02.09