Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get every element in a list of list of lists?

Tags:

python

I'm making a heart game for my assignment but I don't know how to get every element in a list of list:

>>>Cards = [[["QS","5H","AS"],["2H","8H"],["7C"]],[["9H","5C],["JH"]],[["7D"]]]

and what comes to my mind is :

for values in cards:
    for value in values:

But I think I just got element that has 2 list. How to calculate the one that has 3 and 1 list in the cards?

like image 880
Erika Sawajiri Avatar asked May 24 '13 12:05

Erika Sawajiri


People also ask

Can you have a list of list of lists in Python?

Definition: A list of lists in Python is a list object where each list element is a list by itself. Create a list of list in Python by using the square bracket notation to create a nested list [[1, 2, 3], [4, 5, 6], [7, 8, 9]] .

How do I iterate every other item in a list?

Use enumerate() to access every other element in a list {use-for-loop-enumerate} Use the syntax for index, element in enumerate(iterable) to iterate through the list iterable and access each index with its corresponding element .

How do I get a list of elements in a list in Python?

Find an element using the list index() method. To find an element in the list, use the Python list index() method, The index() is an inbuilt Python method that searches for an item in the list and returns its index. The index() method finds the given element in the list and returns its position.


1 Answers

Like this:

>>> 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']

As, nacholibre pointed out, the compiler package is deprecated. This is the source of 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
like image 157
Hans Then Avatar answered Nov 15 '22 22:11

Hans Then