생활
[파이썬]이 두 코드가 무슨 차인지 알고 싶어요.
class Mylist(list):
def replace(self, old, new):
for i in self:
if i == old:
self[self.index(i)] = new
return
a = Mylist([1, 2, 3, 4, 5])
a.replace(2, 4)
a
----결과---
[1, 4, 3, 4, 5]class Mylist(list):
def replace(self, old, new):
new_list = list(map(lambda x : new if x == old else x, self))
self = new_list
a = Mylist((1, 2, 3, 4, 5))
a.replace(2, 4)
a
---결과---
[1, 2, 3, 4, 5]
제가볼땐 위의 코드와 아래의 코드가 같은 결과값이 나와야 한다고 생각하는데.. 왜 기존의 self 에 new list가 할당이 안되나요? ㅠ 뭔가 스코프를 놓치고 있는 것 같은데 궁금합니다!
2개의 답변이 있어요!