city_list = ["Taipei","beijing","wuhan"]
for i in range(len(city_list)):
print('%s: %s' %(i, city_list[i]))
city_list = ["Taipei","beijing","wuhan"]
for idx, city in enumerate(city_list):
print('%s: %s' %(idx, city))
相同的結果但是enumerate函數寫法更加簡潔,且有更高的閱讀性。
#Before
squares = []
for i in range(10):
squares.append(i*i)
print(squares)
# After
squares = [i*i for i in range(10)]
print(squares)
# save memory by generator
import sys
my_list = [i for i in range(100000)]
print(type(my_list))
print(sys.getsizeof(my_list), "bytes")
my_gen =(i for i in range(100000))
print(type(my_gen))
print(sys.getsizeof(my_gen), "bytes")
test_dict = {"name": "Wendy"}
name = test_dict.get("age")
print(name)
test_dict = {"name": "Wendy"}
name = test_dict.get("age", 0)
print(name)
test_dict = {"name": "Wendy", "age": 23}
name = test_dict.get("age", 0)
print(name)
from collections import Counter
my_list = [10,10,10,3,4,4,5,5,5,5]
counter = Counter(my_list)
print(counter)
list_of_strings = ["Hello", "my", "name", "is", "Wendy"]
my_string = ""
for s in list_of_strings:
my_string += s + " "
print(my_string)
建議使用.join()做字串串串接
list_of_strings = ["Hello", "my", "name", "is", "Wendy"]
my_string = " ".join(list_of_strings)
print(my_string)