This exercise is to show you how to count your string occurrences, or how many duplicated value. 我想分享如何找估重複文字次數。
iterate through list, and store in dictionary
[方法一] 基本 loop 把它存在 dictionary
output: {'James': 1, 'Kelly': 2, 'Sammie': 1
1 2 3 4 5 6 7 8 9 10
listofName=['James','Kelly', 'Sammie', 'Kelly'] dictcollect={} for name in listofName: if name in dictcollect: dictcollect[name]+=1
else: dictcollect[name]=1 print(dictcollect)
其實可以寫成更簡短方式,其實跟上面方式一樣
1 2 3 4 5
listofName=['James','Kelly', 'Sammie', 'Kelly'] dictcollect={} for name in listofName: dictcollect[name]=dictcollect.get(name,0)+1 print(dictcollect)
如果沒出現就離開,出現就會+1,也可以這樣做 1+dictcollect.get(name,0)。
dictcollect.get(name, 0) checks if the name already exists as a key in the dictionary. If it exists, the current count is retrieved. If it doesn’t exist, 0 is returned.
Today I would like to share when we see an arrow or colon on function, basically there’s a term Function Annotation. I see some turtorial and see many developer beeen using it, and went and research on it.
You can think it’s just a comment, nothing else. It to tell people about your code expectation, like data type or return value. So let me show you some examples, and you will see the arrow or colon doesn’t mean anything, it just to tell people what this variable mean.
在介紹之前我們在 python 都會用到 re 或是 rex ,但在這我只會分享用 re,也就是要 import re,不然不能用。
常用的 req module
Module
說明
match
Determine if the RE matches at the beginning of the string.
search
Scan through a string, looking for any location where this RE matches
findall
Find all substrings where the RE matches, and returns them as a list.
finditer
Find all substrings where the RE matches, and returns them as an iterator.
compile()
1 2 3 4 5 6
import re text ='https://chenchih.page , Author is ChenChih' pattern=re.compile('Chenchih',re.I) print(pattern.match(text)) #None print(pattern.search(text).group()) #chenchih print(pattern.findall(text)) #['chenchih', 'ChenChih']
output:
None cheenchih > > ['chenchih', 'ChenChih']
match()
This function matches a regular expression pattern at the beginning of a string. If the pattern is found, it returns a match object, otherwise, it returns None.
1 2 3 4 5
import re teststring="123abc456789abc123ABC" pattern=re.compile(r"abc") match=pattern.match(teststring) print(match)