【问题标题】:List comprenhension help python [duplicate]列表理解帮助python [重复]
【发布时间】:2018-08-31 19:39:42
【问题描述】:

我试图更好地理解列表理解:

我有以下代码:

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

如何转换列表理解? 列表理解是否更 Pythonic?

【问题讨论】:

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


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-29
    • 2011-06-15
    • 2019-03-07
    • 1970-01-01
    • 2010-11-12
    • 1970-01-01
    相关资源
    最近更新 更多