![](/img/trans.png)
[英]How can I write the code in such a way that multiple functions get created but I don't have to write the same code again and again?
[英]How to write a code which checks if we have again this same value in index?
connect = {'2': ['1', '3'], '1': ['2'], '3': ['2', '4'], '4': ['3']}
如何编写代码来检查索引中是否再次具有相同的值?
示例:如果我们附加'2':['1']
我们得到:
'2': ['1', '3'] not '2': ['1','1', '3']
def my_append( c, k, v ):
if v not in c[k]:
c[k].append(v)
connect = {'2': ['1', '3'], '1': ['2'], '3': ['2', '4'], '4': ['3']}
print connect
my_append(connect, '2', '1')
print connect
my_append(connect, '2', '4')
print connect
输出:
{'1': ['2'], '3': ['2', '4'], '2': ['1', '3'], '4': ['3']}
{'1': ['2'], '3': ['2', '4'], '2': ['1', '3'], '4': ['3']}
{'1': ['2'], '3': ['2', '4'], '2': ['1', '3', '4'], '4': ['3']}
根据您是否不需要保留顺序,您可以将列表值转换为集合,因为集合不允许重复。
connect = {'2': ['1', '3'], '1': ['2'], '3': ['2', '4'], '4': ['3']}
set_connect = {k: set(v) for k, v in connect.items()}
print(set_connect)
set_connect['2'].add('1')
print(set_connect)
set_connect['2'].add('5')
print(set_connect)
输出
{'2': {'1', '3'}, '1': {'2'}, '3': {'4', '2'}, '4': {'3'}}
{'2': {'1', '3'}, '1': {'2'}, '3': {'4', '2'}, '4': {'3'}}
{'2': {'5', '1', '3'}, '1': {'2'}, '3': {'4', '2'}, '4': {'3'}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.