鱼C论坛

 找回密码
 立即注册
查看: 1687|回复: 0

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

[复制链接]
发表于 2019-9-24 16:22:55 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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))







   
   

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-11-16 09:58

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表