【问题标题】:How do I create new string list with all matchings from a previous list?如何使用以前列表中的所有匹配项创建新的字符串列表?
【发布时间】:2015-08-18 19:48:19
【问题描述】:

我正在尝试用 python 制作一个基本的二十一点游戏,我想创建一个名为 Deck 的新列表。我希望Deck 在一个列表中包含所有可能的套装/等级配对(即红心 A、红心 2、红心 3 等),这样我就可以以random.shuffle.pop 风格开始“交易” .

如何将这两个列表配对,还是必须自己输入?

这是当前代码:

print ("Welcome to the Blackjack Table! May I have your name?")
user_name = input("Please enter your name:")
print ("Welcome to the table {}. Let's deal!".format(user_name))
import random

suits = ["Heart", "Diamond", "Spade", "Club"]
ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
values = {'A':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10, 'J':10, 'Q':10, 'K':10,}

deck = 

【问题讨论】:

    标签: python string list python-3.x multiplication


    【解决方案1】:

    使用嵌套的list comprehension 将每个等级与每个花色配对。

    deck = [(rank, suit) for rank in ranks for suit in suits]
    

    itertools.product 可以用来完成同样的事情:

    import itertools
    deck = list(itertools.product(ranks, suits))
    

    【讨论】:

    • 谢谢!很有帮助。
    【解决方案2】:

    因此,您要做的就是将每套西装与每个等级配对。下面的代码正是用两个嵌套的for loops 来实现的:

    deck = []  # create an empty list
    for suit in suits: 
        for rank in ranks:
            deck.append((suit, rank))  # append a tuple to the list
    print len(deck)  # prints 52, as expected
    

    更 Python 的方式是使用 list comprehension。它有点快,但可能不太(或更多)直观。

    deck = [(suit, rank) for suit in suits for rank in ranks]
    

    【讨论】:

    • 我自己发现列表理解更直观。但顺便说一句,您的两个版本并不完全相同,因为它们会以不同的顺序列出列表,尽管它们最终会包含相同的值。
    • @Cyphase 很好发现,我修复了列表理解。我也更喜欢列表理解,但对于没有数学背景或来自其他语言的人来说,使用 for 可能更容易理解。
    猜你喜欢
    • 2020-02-24
    • 2017-10-21
    • 1970-01-01
    • 2018-03-06
    • 2019-09-21
    • 1970-01-01
    • 2019-02-03
    • 2018-07-11
    • 2020-04-21
    相关资源
    最近更新 更多