列表comprenhension帮助python

时间:2018-03-22 11:25:24

标签: python python-3.x list-comprehension

我想更好地理解列表理解:

我有以下代码:

deck = [] 
for rank in ranks:
    for suit in suits:
        deck.append(('%s%s')%(rank, suit))

如何在列表理解中进行转换? 如果列表理解与否,它是否更具pythonic?

1 个答案:

答案 0 :(得分:1)

ranks = [1,2,3,4,5]
suits = [10,11,12,13,14,15]

deck = [] 
for rank in ranks:
    for suit in suits:
        deck.append(('%s%s')%(rank, suit))


deck_comp = [('%s%s')%(rank, suit) for rank in ranks for suit in suits]

print(deck == deck_comp)