a = [1,2,3] 和 b = [(1),(2),(3)] 以及 c = [(1,),(2,),(3,)] 的区别?
a = [1,2,3] 和 b = [(1),(2),(3)] 是数字类型,c = [(1,),(2,),(3,)] 是元祖类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# 补充1:a=[1,2,3,4,5],b=a和b=a[:],有区别么?
a = [1,2,3,4,5] b = a b1 = a[:] print(b) # [1, 2, 3, 4, 5] print(b1) # [1, 2, 3, 4, 5]
b.append(6) print("a", a) # a [1, 2, 3, 4, 5, 6] print("b", b) # b [1, 2, 3, 4, 5, 6] # 传递引用 print("b1",b1) # b1 [1, 2, 3, 4, 5] # 浅拷贝
# 补充2:一个列表 A=[2, 3, 4],Python 如何将其转换成 B=[(2,3),(3,4),(4,2)]? A = [2, 3, 4] B = zip(A, A[1:]+A[:1])
列表推导式和生成器表达式
1
1 2 3 4 5 6 7 8 9 10
print([i*i for i in [1, 2, 3]]) # [1, 4, 9]
defmultipliers(): return [lambda x:i*x for i in range(4)] print([m(2) for m in multipliers()]) # 6,6,6,6
# 解释: # 函数返回值为一个列表推导式,经过 4 次循环结果为包含 4 个 lambda 函数的列表 # 由于函数未被调用,循环中的 i 值未被写入函数,经过多次替代,循环结束后 i 值为 3, # 故结果为:6,6,6,6
请修改 multipliers 的定义来产生期望的结果(0,2,4,6)
1 2 3
defmultipliers(): return (lambda x:i*x for i in range(4)) # 返回一个生成器表达式 print([m(2) for m in multipliers()])
2
1 2 3 4 5 6
items = [1, 2, 3, 4] print([i for i in items if i > 2]) # [3, 4] print([i for i in items if i % 2]) # [1, 3] print([(x, y) for x, y in zip('abcd', (1, 2, 3, 4, 5))]) # [('a', 1), ('b', 2), ('c', 3), ('d', 4)] print({x: f'item{x ** 2}'for x in (2, 4, 6)}) # {2: 'item4', 4: 'item16', 6: 'item36'} print(len({x for x in'hello world'if x notin'abcdefg'}))# 6
defreverse_list(li): n = len(li) for i in range(n // 2): li[i], li[n-i-1] = li[n-i-1], li[i] return li
# print(reverse_list([1,2,3,4,5,6]))
数字反转,不用切片,不用内置函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# 123->321 12300->321 defreverse_int(num): is_neg = False if num < 0: is_neg = True num = -1 * num res = 0 while num > 0: res = res * 10 res += num % 10 num = num // 10 if is_neg: res = res * -1 return res
# print(reverse_int(-123001))
数字转列表
1 2 3 4 5 6 7 8 9
defint2list(num): li = [] while num > 0: li.append(num % 10) num = num // 10 li.reverse() return li