python

Python

This note is using for recording learn python language.

创建 list

1
2
3
4
res = list()
for i in range(5):
res.append(i)
print(res)

list 也可以用于转换

1
2
res = list("Hello") # covert into ['h', 'e', 'l', 'l', 'o']
res = list((1,2,3)) # convert int [1,2,3]

连接符 join

"".joint(res) 将list res按 "" 链接起来

1
2
3
4
5
6
7
8
res = ["h", "e", "l", "l", "o"]
result = "".join(res)
print(result) # hello


res = ["2025", "01", "13"]
result = "-".join(res)
print(result) # 2025-01-13

上面 的 res 中必须都是字符串

1
2
3
res = ["a", "b", 1]
result = "".join(map(str, res)) # 使用map转换为字符串
print(result) # ab1

Map函数

1
map(fuction, iterable)

function: 内置函数, 自定义函数, lumbada

Iterable: 1个or多个迭代对象 : list, tuple, or string

返回值需要通过 list() or tuple() 进行转换

1
2
3
nums = [1, 2, 3]
square = map(lambda x: x ** 2, nums)
print(list(square)) # [1,4,9]
1
2
3
4
nums1 = [1,2,3]
nums2 = [1,2,3]
square = map(lambda x, y: x + y: nums1, nums2)
print(list(square)) # [1, 4, 9]
1
2
3
strs = ["1", "2", "3"]
ints = map(int, strs)
print (list(ints)) # [1, 2, 3]
1
2
3
4
5
6
def to_uppercase(s):
return s.upper()

words = ["hello"]
upper_words = map(to_uppercase, words)
print(list(upper_words)) # "HELLO"