python - 在 python 中使用巨大的列表

标签 python python-itertools poker

我如何管理一个包含 100 多万个字符串的庞大列表? 我如何开始处理如此庞大的列表?

示例大列表:

cards = [
            "2s","3s","4s","5s","6s","7s","8s","9s","10s","Js","Qs","Ks","As"
            "2h","3h","4h","5h","6h","7h","8h","9h","10h","Jh","Qh","Kh","Ah"
            "2d","3d","4d","5d","6d","7d","8d","9d","10d","Jd","Qd","Kd","Ad"
            "2c","3c","4c","5c","6c","7c","8c","9c","10c","Jc","Qc","Kc","Ac"
           ]

from itertools import combinations

cardsInHand = 7
hands = list(combinations(cards,  cardsInHand))

print str(len(hands)) + " hand combinations in texas holdem poker"

最佳答案

有很多很多的内存。 Python 列表和字符串实际上相当高效,所以只要您有足够的内存,这应该不是问题。

就是说,如果您存储的是具体的扑克手牌,您绝对可以想出更紧凑的表示形式。例如,你可以用一个字节来编码每张牌,这意味着你只需要一个 64 位的 int 来存储一整手牌。然后,您可以将它们存储在 NumPy 数组中,这比 Python 列表更有效。

例如:

>>> cards_to_bytes = dict((card, num) for (num, card) in enumerate(cards))
>>> import numpy as np
>>> hands = np.zeros(133784560, dtype='7int8') # 133784560 == 52c7
>>> for num, hand in enumerate(itertools.combinations(cards, 7)):
...     hands[num] = [cards_to_bytes[card] for card in hand]

为了加快最后一行的速度:hands[num] = map(cards_to_bytes.__getitem__, hand)

这只需要 7 * 133784560 = ~1gb 的内存……如果你将四张卡片放入每个字节中,这可能会减少(我不知道这样做的语法……)

关于python - 在 python 中使用巨大的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15283893/

相关文章:

python - 从嵌套列表中删除相似元素

java - 基本扑克程序 - 打印牌组

algorithm - 我可以在这里做得比二进制搜索更好吗?

python - Django Admin 修改模型继承

android - 如何使用appium自动化android手机后退按钮

python - 如何将字符串字典转换为列表到字典列表?

c++ - 随机洗牌查询

python - 将聊天响应放入 GPT API 中的列表中

Python Pandas : Convert timedelta Value From Subtracting Two Dates Into Integer Datatype (AttributeError)

python - 用于组合异步迭代器的映射、过滤器和 itertools