Skip to main content
 首页 » 编程设计

python之如何将这段 Python 代码写得更短

2025年05月04日13虾米哥

我正在制作一个修改过的二十一点游戏。只玩牌 2 到 9。这副牌中没有十张牌、花牌或 A。

首先,我创建了变量 deck,它采用一个空列表。
然后,我创建了 4 个 for 循环 以将卡片列表附加到卡片组。

我想知道是否有更短的写法:

import random 
 
deck = [] 
for list_of_cards in range(2, 10): 
    spades = 'spades' 
    list_of_spades = str(list_of_cards) + ' of' + ' ' + spades 
    deck.append(list_of_spades) 
for list_of_cards in range(2, 10): 
    clubs = 'clubs' 
    list_of_clubs = str(list_of_cards) + ' of' + ' ' + clubs 
    deck.append(list_of_clubs) 
for list_of_cards in range(2, 10): 
    diamonds = 'diamonds' 
    list_of_diamonds = str(list_of_cards) + ' of' + ' ' + diamonds 
    deck.append(list_of_diamonds) 
for list_of_cards in range(2, 10): 
    hearts = 'hearts' 
    list_of_hearts = str(list_of_cards) + ' of' + ' ' + hearts 
    deck.append(list_of_hearts) 

结果就像我想要的那样:

['2 of spades', '3 of spades', '4 of spades', '5 of spades', '6 of spades', '7 of spades', '8 of spades', '9 of spades', '2 of clubs', '3 of clubs', '4 of clubs', '5 of clubs', '6 of clubs', '7 of clubs', '8 of clubs', '9 of clubs', '2 of diamonds', '3 of diamonds', '4 of diamonds', '5 of diamonds', '6 of diamonds', '7 of diamonds', '8 of diamonds', '9 of diamonds', '2 of hearts', '3 of hearts', '4 of hearts', '5 of hearts', '6 of hearts', '7 of hearts', '8 of hearts', '9 of hearts'] 

因为我是 Python 的新手,所以我假设有一种方法可以将它写得更短。感谢您的帮助!

请您参考如下方法:

为什么需要 4 个循环?为什么需要创建那些无用的字符串? (+ 'of' + ' ' + spades 与 ' of spades' 相同...)(我也修复了一些其他问题)

deck = [] 
for n in range(2, 10): 
    deck.append('%i of spades' % n) 
    deck.append('%i of hearts' % n) 
    deck.append('%i of diamonds' % n) 
    deck.append('%i of clubs' % n) 

或者,使用嵌套循环:

deck = [] 
for n in range(2, 10): 
    for s in ['spades', 'hearts', 'diamonds', 'clubs']: 
        deck.append('%i of %s' % (n, s))