Python(4)

lst = [1,2,4,8,16,32,64,128,256,512,1024,32769,65536,4294967296]

 # 输出
 {
 1:[1,2,3,8],
 2:[16,32,64],
 3:[128,256,512],
 4:[1024,],
 5:[32769,65536],
 6:[4294967296]
 }
dic={}
for i in lst:
    len_i=len(str(i))
    dic.setdefault(len_i,[]).append(i)
print(dic)
View Code

请尽量用简洁的方法将二维数组转换成一维数组

  例: 转换前 lst=[[1,2,3],[4,5,6],[7,8,9]]

     转换后 lst = [1,2,3,4,5,6,7,8,9] 

lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
 #列表推导式
  lst=[j for i in lst for j in i]
  print(lst)

  #for循环
  a=[]
  for i in lst:
      a.extend(i)
  lst=a
 print(lst)
View Code
给定两个 list:A,B,请用 Python 找出 A,B 中相同的元素,A,B 中不同的元素

复制代码
 1 A=[1,3,7,0,5,11]
 2 B=[11,4,6,8,0]
 3 # 方法一:列表操作
 4 s=[i  for i in A for j in B if j==i]
 5 print(s)
 6 d=[]
 7 for i in A:
 8     if i not in s:
 9         d.append(i)
10 for i in B:
11     if i not in s:
12         d.append(i)
13 print(d)
14 
15 #方法二:集合操作
16 s=set.intersection(set(A),set(B))
17 d=set.difference(set.union(set(A),set(B)),set(s))
18 print(s)
19 print(d)
原文地址:https://www.cnblogs.com/topass123/p/12577735.html