我正在为我的作业制作心脏游戏,但我不知道如何在列表列表中获取每个元素:
>>>Cards = [[["QS","5H","AS"],["2H","8H"],["7C"]],[["9H","5C],["JH"]],[["7D"]]]
而我想到的是:
for values in cards: for value in values:
但我想我的元素有2个列表.如何计算卡中有3个和1个列表的那个?
像这样:
>>> Cards = [[["QS","5H","AS"],["2H","8H"],["7C"]],[["9H","5C"],["JH"]],["7D"]] >>> from compiler.ast import flatten >>> flatten(Cards) ['QS', '5H', 'AS', '2H', '8H', '7C', '9H', '5C', 'JH', '7D']
正如nacholibre指出的那样,该compiler
软件包已被弃用.这是以下来源flatten
:
def flatten(seq): l = [] for elt in seq: t = type(elt) if t is tuple or t is list: for elt2 in flatten(elt): l.append(elt2) else: l.append(elt) return l
略显模糊的oneliner:
>>> [a for c in Cards for b in c for a in b] ['QS', '5H', 'AS', '2H', '8H', '7C', '9H', '5C', 'JH', '7', 'D']
您可能想要给出a,b和c更具描述性的名称.