如何解决如何从字典中的列表中删除元组?
如何从字典中的列表中删除元组?如有必要,将这个删除的元组放在另一本字典中?
{'name': '...','hand_cards': [('...',...),('...',...)]}
解决方法
假设你的字典(根据你写的内容)是这样的
diction = {'name': 'Name','hand_cards': [('A',0),('B',1),('C',2)]}
如果你想删除一个你知道满足条件的元组,假设你想删除 x=('B',1) 元组,对于 x[0]='B' 和 x[1 ]=1 然后遍历每个元组并检查这个(或那些)条件。
# New dictionary to save removed tuple(s)
new_diction = {}
# Or dictionary with list containing all removed tuples
new_diction2 = {'hand_cards':[]}
# Run through each tuple inside the list of dictionary with key='hand_cards'
for tupl in diction['hand_cards']:
if tupl[0]=='B':
diction['hand_cards'].remove(tupl)
new_diction['hand_cards'] = tupl # Add tuple to new dictionary
new_diction2['hand_cards'].append(tupl) # Add tuple to a list in the new dictionary
结果:
>>> diction
{'name': 'Name',2)]}
>>> new_diction
{'hand_cards': ('B',1)}
>>> new_diction2
{'hand_cards': [('B',1)]}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。