opop52 发表于 2019-9-24 16:22:55

新手求帮忙,如何筛选字典中唯一键值的元素,并组成新的字典

新手求帮忙,如何筛选字典中唯一键值的元素,并组成新的字典

自己写的代码附上,对于函数list_for_one_one(dict)不知道哪里出错,有时候达不到上述要求,求大神帮忙看看




import random
import sys


#==============function

def intersection(list1,list2):
    lista = []
    for each in list2:
      if each not in list1:
            lista.append(each)

    return lista

def list_for_value(list1,dict):
    listb = []
    for each in list1:
      if each not in keys:
            listb.append(None)
      else:
            listb.append(dict)

    return listb



# judge if a list contains the same elements
def iscontain(list,a):
    if a not in list:
      list.append(a)
    else:
      return
   
def list_for_one_one(dict):
    dict2 = dict
    values_temp = []
    keys_temp = []
    index = 0
   
    for each in keys:
      while index < len(keys):
            a = keys
            if dict == dict:
                iscontain(keys_temp,each)
                iscontain(keys_temp,a)
                index = index + 1
            else:
                index = index + 1                        
    for each in keys_temp:
      dict2.pop(each)
    return dict2

      
#===================by Zhirong Wen
temp = input('Enter two intergers(Please separate them with space):')
Integer = temp.split()

try:
    Integer1 = int(Integer)
    Integer2 = int(Integer)
except ValueError:
    print('Input is incorrect.')
    sys.exit()
if len(Integer) != 2:
    print('Input is incorrect.')
    sys.exit()


   
Integer =
Integer.sort()
#print(Integer)


#keys_number and zip dict1
keys_number = random.randint(Integer, Integer)
keys = []
values = []

while keys_number != 0:
    keys.append(random.randint(Integer, Integer))
    values.append(random.randint(Integer, Integer))
    keys_number = keys_number-1

dict1 = dict(zip(keys,values))


#not in mapping and represented as list
list_Integer = range(Integer,Integer+1)



#outcome
print('The generated mapping is: ','\n',dict1)
print('The mappings\'s so-called "keys" make up a set whose number of elements is:','\n',len(dict1))
print('The list of integers between ',Integer,' and ',Integer ,' that are not keys of the mapping is:','\n',intersection(keys,list_Integer))
print('Represented as a list, the mapping is:','\n',list_for_value(list_Integer,dict1))
print('The one-to-one part of the mapping is:','\n',list_for_one_one(dict1))







   
   

页: [1]
查看完整版本: 新手求帮忙,如何筛选字典中唯一键值的元素,并组成新的字典