【问题标题】:How can i remove a tuple from a list in a dictionary?如何从字典中的列表中删除元组?
【发布时间】:2021-01-17 08:50:42
【问题描述】:

如何从字典列表中删除元组?如有必要,将这个已删除的元组放入其他字典中?

{'name': '...', 'hand_cards': [('...', ...), ('...', ...), ('...', ...)]}

【问题讨论】:

  • 似乎'hand_cards' 的所有值都是元组列表。所以只需重新定义'hand_cards' = []。你能指定更详细的问题吗?
  • 很难重新定义手牌,因为对于每个玩家,handcard_list 都会被重置,这样新牌就不会和旧牌混在一起

标签: python list dictionary tuples


【解决方案1】:

假设你的字典(根据你写的)看起来像这样

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', 'hand_cards': [('A', 0), ('C', 2)]}

>>> new_diction           
{'hand_cards': ('B', 1)}

>>> new_diction2              
{'hand_cards': [('B', 1)]}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 2014-06-29
    • 2020-07-14
    • 1970-01-01
    相关资源
    最近更新 更多