欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

数组a,b :数组b是数组a的子集,去掉数组b中不符合该条件的元素

程序员文章站 2024-03-15 20:12:12
...

案例一:列表

a=[1,2,3,4,5,6]
b=[3,5,0]
print(a,b)
flag=[]
for i in range(0,len(b)):
     flag.append(0)
     for j in a:
         if b[i]==j:
              flag[i]=1
              break 
print(flag)
for i in range(0,len(b)):
    if flag[i]==0:
         b.remove(b[i])
print(b)             
     

输出:

([1, 2, 3, 4, 5, 6], [3, 5, 0])
[1, 1, 0]
[3, 5]

案例2:字典


G={"A":{"B","D"},
    "B":{"C","E"},
    "C":{"E","F"},
    "D":{"G"},
    "E":{"D","F","G","H","M"},
    "F":{"H"},
    "G":{"H"},
    "H":{}}

def com(a,b):
    flag=[]
   
    print("b:",type(b),b)

    for i in range(0,len(b)):
       # print("b[i]:",b[i])
        flag.append(0)
        #print("b[i]:",b[i])
        for j in range(0,len(a)):
            if b[i]==a[j]:
                flag[i]=1
                #print("success")
                break 

    #print("flag:",flag)
    for i in range(0,len(b)):
        if flag[i]==0:
            print("error")
            b.remove(b[i])
    print("b",b)       
    return b


a=[]
b=[]
c=[]
for i,j in  G.items():
      a.append(i)  
print("a:",a)
for i,j in G.items():
    if i=="E":
      b.append(j)
      for n in b:
           data=n
      for y in data: 
         c.append(y)
      print("c:",c)
      c=com(a,c)
      print("c:",c,type(c),"i",i)
      G[i]=c
      b.pop(0)
print(G)

输出:

G={"A":{"B","D"},

"B":{"C","E"},

"C":{"E","F"},

"D":{"G"},

"E":{"D","F","G","H"},

"F":{"H"},

"G":{"H"},

"H":{}}