質問

I have a very particular problem, I have a deck of cards. The deck is a list of lists of tuples, each internal list is a suit with card tuples (suit, value), sorted smallest to largest(2-Ace). I would like to find the smallest card in the deck. So basically I want to take the first object from each suit, and find the smallest. Short of an horridly ugly for loop, what is the most pythonic way to do this?

役に立ちましたか?

解決

min takes a key function. You can use this to get the first element to use it as the comparison:

min(my_list, key=lambda x: x[0])

他のヒント

min(suit[0] for suit in deck, key=lambda suit,value: value)

Since you noted that the suits are sorted, you can simply get the first item of each suit list to get the smallest value of that suit; then compare those first values using min() with the key argument specified to look at the value portion of each.

Lets assume that the deck list is created as below:

TheHearts = TheSpades = TheDiamonds = TheClubs = [2,3,4,5,6,7,8,9,10,"j","q","k","a"]
TheDeck = [TheHearts, TheSpades, TheDiamonds, TheClubs]

the following line can provide you the first object of the first list:

print TheDeck[0][0]

or even if you make a dictionary, then you can use the names instead of numbers:

TheHearts = TheSpades = TheDiamonds = TheClubs = [2,3,4,5,6,7,8,9,10,"j","q","k","a"]
TheDeck = {'TheHearts':TheHearts, 'TheSpades':TheSpades, 'TheDiamonds':TheDiamonds, 'TheClubs':TheClubs}
print TheDeck['TheHearts'][0]
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top