列出要添加到字典中的值

List values being added to dictionary

提问人:Brad Richerson 提问时间:11/16/2023 最后编辑:S.BBrad Richerson 更新时间:11/17/2023 访问量:32

问:

我正在尝试创建一个字典,但它一直将字符串拆分为 和 .如何解决此问题?"10""1""0"

suits = ['h', 'd', 's', 'c']
values = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
cards = {"h" : [], 'd': [], 's': [], 'c': []}

for suit in cards:
    for value in values:
        cards[suit] += value

print(cards)

输出:

{'h': ['A', '2', '3', '4', '5', '6', '7', '8', '9', '1', '0', 'J', 'Q', 'K'], 'd': ['A', '2', '3', '4', '5', '6', '7', '8', '9', '1', '0', 'J', 'Q', 'K'], 's': ['A', '2', '3', '4', '5', '6', '7', '8', '9', '1', '0', 'J', 'Q', 'K'], 'c': ['A', '2', '3', '4', '5', '6', '7', '8', '9', '1', '0', 'J', 'Q', 'K']}

如何阻止值 10 被拆分为 1 和 0?

python 列表 字典

评论


答:

1赞 S.B 11/17/2023 #1

代码的简单修复是更改:

cards[suit] += value

自:

cards[suit].append(value)

请记住,您可以将任何可迭代对象(不仅仅是列表)放入列表运算符的右侧。它基本上遍历该可迭代对象并将它们附加到原始列表中:+=

lst = []
lst += "10"
print(lst)   # ['1', '0']

您不希望这种“扩展”行为,因此请改用项目。.append()

0赞 user_stack_overflow 11/17/2023 #2

就是这样:

suits = ['h', 'd', 's', 'c']
values = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
cards = {}

for suit in suits:
    for value in values:
        if suit not in cards.keys(): 
            a=[]
            a.append(value)
            cards[suit]=a
        else:
            cards[suit].append(value)
        
print(cards)

输出:

{'h': ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'], 
'd': ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'], 
's': ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'], 
'c': ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']}