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?
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]] .
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 .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With