Python Basics4 :Transforming Sequences オブジェクトの上書きmutation

9.1.1. Learning Goals

  • To understand the concepts of mutable and immutable data types
  • To understand that methods on strings leave the origninal string alone but return a new string
  • To understand that lists are mutable data types and that mutating methods on lists return None

 

Mutability of list リストは可変

Unlike strings, lists are mutable. This means we can change an item in a list by accessing it directly as part of the assignment statement.

 

removeというメソッドでも消せる。

 

こうすると、文字の置換ができる!

sent = "The mall has excellent sales right now."
wrds = sent.split()
wrds[1] = 'store'
new_sent = " ".join(wrds)

 

listのelementをindexで指定してassignし直しても置換ができる。

 

 

listに使えるメソッド

mutatorはlistを変える。

mutationはidを変えない(別のオブジェクトを作らない)?

hybridはassignしないと使えない?

 

The word mutator means that the list is changed by the method but nothing is returned (actually None is returned). A hybrid method is one that not only changes the list but also returns a value as its result. Finally, if the result is simply a return, then the list is unchanged by the method.

 

mylist = []
print("append and insert")
mylist.append(5) #listの最後に5を加える。
mylist.append(27)
mylist.append(3)
mylist.append(12)
print(mylist)

mylist.insert(2, 12)#listのindex number2 の位置に12というvalueを加える。
print(mylist)
print(mylist.count(12))#listの中に12というvalueを持つitemがいくつあるか

print("index and count")
print(mylist.index(3))#valueが3と合致するitemが最初に出てくるindex number
print(mylist.count(5))

print("reverse and sort")
mylist.reverse()#listのitemの順序を逆にする。
print(mylist)

mylist.sort()#listを小さい順に並び替える。
print(mylist)
print("remove, del, and pop")
mylist.append(5)
print(mylist)
#valueが5のitemのうち、一番小さなindexnumberをlistから取り除く。
mylist.remove(5)
print(mylist)
#valueが5のitemのうち、一番小さなindexnumberをlistから取り除く。
mylist.remove(5)
print(mylist)
del mylist[0] #index numberが0のitemをlistから取り除く。
print(mylist)
lastitem = mylist.pop()#index number最後のitemをlistから取り除く。
print(lastitem)
print(mylist)

The Accumulator Pattern with Lists

numbs = [5, 10, 15, 20, 25]

for i in range(len(numbs)):
  numbs[i] += 5
  print(numbs)
print(numbs)

numbs = [5, 10, 15, 20, 25]
newlist = []
for i in numbs:
  newlist.append(i+5)
  print(newlist)
print(newlist)

appendの便利なところ

9.9. Non-mutating Methods on Strings stringに使えるメソッド

countは使えるなー

print(“upper and lower メソッド”)
ss = “Hello, World”
print(ss.upper())
tt = ss.lower()
print(tt)
#listメソッドと違い、mutateされない。
print(ss)

print(“stripe and replaceメソッド”)
ss = ” Hello, World ”
print(ss)
print(“***”+ss.strip()+”***”)
news = ss.replace(“o”, “***”)
print(news)
print(ss)

The Accumulator Pattern with Strings

stringにはappendメソッドはない???

object = object + “string” だとid変わる

object += “string” だとid変わらない(appendと同じ)。←listには使わないことを推奨されている。

謎すぎる。

print("idが16のobjectが二つ生成されている。なぜ?")
s = "ahdn"
print("ac")
ac = ""
print(ac)
for c in s:
ac = ac + c + "-" + c + "-"
print(id(ac))
print(ac)

t = "lmk"
print("ad")
ad = ""
for d in t:
ad += d + "-" + d + "-"
print(id(ad))
print(ad)

u = "aseZ"
print("ae")
ae = ""
for e in u:
ae = ae + e + "-" + e + "-"
print(id(ae))
print(ae)

よくわからんけど面白いやつ。string format メソッド

scores = [(“Rodney Dangerfield”, -1), (“Marlon Brando”, 1), (“You”, 100)]
for person in scores:
name = person[0]
score = person[1]
print(“Hello {}. Your score is {}.”.format(name, score))

 

range(len())使わなくていい!

loop の中にsequenceをmutateする操作を入れるとバグる。

9.13. 👩‍💻 Don’t Mutate A List That You Are Iterating Through

 

Final exam

scores = “67 80 90 78 93 20 79 89 96 97 92 88 79 68 58 90 98 100 79 74 83 88 80 86 85 70 90 100”

score_s = scores.split()
print(score_s)

a_scores = 0
for i in score_s:
if int(i) >= 90:
a_scores += 1

 

stopwords = [‘to’, ‘a’, ‘for’, ‘by’, ‘an’, ‘am’, ‘the’, ‘so’, ‘it’, ‘and’, “The”]
org = “The organization for health, safety, and education”

orgs = org.split()
print(orgs)

for i in stopwords:
if i in orgs:
orgs.remove(i)
print(orgs)

acro = “”
for i in orgs:
acro += i[0].upper()

 

 

 

stopwords = [‘to’, ‘a’, ‘for’, ‘by’, ‘an’, ‘am’, ‘the’, ‘so’, ‘it’, ‘and’, ‘The’]
sent = “The water earth and air are vital”

sents = sent.split()
print(sents)

for i in stopwords:
if i in sents:
sents.remove(i)
print(sents)

acro = “”
for i in sents:
if i != “vital”:
acro += i[:2].upper() + “. ”
elif i == “vital”:
acro += i[:2].upper()

print(acro)

 

 

p_phrase = “was it a car or a cat I saw”
r_phrase =””
for i in range(len(p_phrase)):
r_phrase += p_phrase[-1-i]

print(r_phrase)

inventory = [“shoes, 12, 29.99”, “shirts, 20, 9.99”, “sweatpants, 25, 15.00”, “scarves, 13, 7.75”]
inventories = []
for i in range(len(inventory)):
inventories += inventory[i].split(“, “)
print(inventories)

for i in range(len(inventory)):
name = “”
name = inventories[i*3]
stock = “”
stock = inventories[i*3+1]
price = “”
price = inventories[i*3+2]
print(“The store has {} {}, each for {} USD.”.format(stock, name, price))

course_2_assessment_6

まじこれ何無理。while使えませんでした。

Write a function called check_nums that takes a list as its parameter, and contains a while loop that only stops once the element of the list is the number 7. What is returned is a list of all of the numbers up until it reaches 7.

def check_nums(list):
nums = []
#まずlistのなかに7があればそのidをゲットする。
if 7 in list:
for i in range(list.index(7)):
nums.append(list[i])
return nums
else:
return list

list = [9,302,4,62,78,97,10,7,8,23,53,1]
nums = check_nums(list)
print(nums)

これだ!使ってるよー。

def sublist(list):
accum = 0
sub = []
#whileの途中でifを挟んでbreakの機能をさせている。
while accum < len(list):
if list[accum]== 7:
return sub
else:
sub.append(list[accum])
accum = accum +1
return sub

list = [9,302,4,62,78,97,10,7,8,23,53,1]
print(sublist(list))

def stop_at_z(list):
accum = 0
sub = []
#whileの途中でifを挟んでbreakの機能をさせている。
while accum < len(list):
if list[accum]== “z”:
return sub
else:
sub.append(list[accum])
accum = accum +1
return sub

list = [‘c’, ‘b’, ‘d’, ‘zebra’, ‘h’, ‘r’, ‘z’, ‘m’, ‘a’, ‘k’]
result = stop_at_z(list)
print(result)

 

sum1 = 0

lst = [65, 78, 21, 33]

for x in lst:
sum1 = sum1 + x

sum2 = 0
accum = 0
while accum < len(lst):
sum2 = sum2 + lst[accum]
accum = accum +1

 

def beginning(list):
accum = 0
sub = []
#whileの途中でifを挟んでbreakの機能をさせている。
while accum < 10:
if list[accum]== “bye”:
return sub
else:
sub.append(list[accum])
accum = accum +1
return sub

list =[‘hello’, ‘hi’, ‘hiyah’, ‘howdy’, ‘what up’, ‘whats good’, ‘holla’, ‘good afternoon’, ‘good morning’, ‘sup’, ‘see yah’, ‘toodel loo’, ‘night’, ‘until later’, ‘peace’, ‘bye’, ‘good-bye’, ‘g night’]
result = beginning(list)
print(result)

 

 

コメント