为什么要更改此字符串

时间:2020-03-28 16:25:06

标签: python python-3.x

cards = ['K', 'Q', 'J', '10', 'Z']
holding = []
for card in cards:
    if card != 'Z':
        holding.extend(card)
print(holding)

输出为:

['K', 'Q', 'J', '1', '0']

为什么不['K', 'Q', 'J', '10']

3 个答案:

答案 0 :(得分:3)

.extend遍历赋予它的元素,并将它们逐一添加(请参阅link)

您添加了'10'作为字符串,并因此遍历了其中的每个元素。因此,请使用.append或输入10作为整数(如果其他代码段都可以)。

答案 1 :(得分:3)

如其他答案所述,使用extend()导致了问题。

但是,如果您只想删除所有出现的“ Z”,则可以使用如下所示的单线列表理解:

cards = ['K', 'Q', 'J', '10', 'Z']
holdings = [card for card in cards if card != 'Z']
print(holdings)

输出:

['K', 'Q', 'J', '10']

详细了解列表理解here

答案 2 :(得分:2)

您打算使用append()

cards = ['K', 'Q', 'J', '10', 'Z']
holding = []
for card in cards:
    if card != 'Z':
        holding.append(card)
print(holding)

extend()方法将参数视为可迭代的,并遍历该参数并添加每个元素。因此,参数'10'['1','0']相同。

相关问题