|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
新手求帮忙,如何筛选字典中唯一键值的元素,并组成新的字典
自己写的代码附上,对于函数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[each])
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[index+1]
if dict[each] == dict[a]:
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[0])
Integer2 = int(Integer[1])
except ValueError:
print('Input is incorrect.')
sys.exit()
if len(Integer) != 2:
print('Input is incorrect.')
sys.exit()
Integer = [Integer1,Integer2]
Integer.sort()
#print(Integer)
#keys_number and zip dict1
keys_number = random.randint(Integer[0], Integer[1])
keys = []
values = []
while keys_number != 0:
keys.append(random.randint(Integer[0], Integer[1]))
values.append(random.randint(Integer[0], Integer[1]))
keys_number = keys_number-1
dict1 = dict(zip(keys,values))
#not in mapping and represented as list
list_Integer = range(Integer[0],Integer[1]+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[0],' and ',Integer[1] ,' 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))
|
|