My example array for this problem is:
fruits = [[apples, oranges], [pears, grapes]]
How could I find which array apples
is in (fruits[0]
or fruits[1]
) and then show the value for fruits[0][1]
with this information?
(more explanation if needed)
If I were to have the code:
choice = input('Enter a fruit: ')
fruits = [[apples, oranges], [pears, grapes]]
print('The fruit grouped with', choice, 'in the 2D array is', <variable>)
How could I change it to produce the output:
<< Enter a fruit: apples
>> The fruit grouped with apples in the 2D array is oranges
CodePudding user response:
You can check if a string is in an list of strings using in
:
'oranges' in ['apples', 'oranges']
# True
You can combine this with a list comprehension and a condition to get a list of items where this condition is True:
fruits = [['apples', 'oranges'], ['pears', 'grapes']]
# for each group in collection
# | |
# V V
[group for group in fruits if 'grapes' in group]
# |___________________|
# |
# give me that group if the condition is true
# It's results in a list of lists because there could be more than one
# [['pears', 'grapes']]
If you know there will only be one, you can ask for the next
one. Passing None
as a second argument give a default. You could also put something like an empty list there if it makes more sense for your problem:
fruits = [['apples', 'oranges'], ['pears', 'grapes']]
choice = 'pears'
next((group for group in fruits if choice in group), None)
# ['pears', 'grapes']
choice = 'oranges'
next((group for group in fruits if choice in group), None)
# ['apples', 'oranges']
choice = 'bannanas'
next((group for group in fruits if choice in group), None)
# None
CodePudding user response:
You'll need to use a nested for loop so you can go through each item in the 2D array.
So let's say for fruits[basket][fruit]
:
- An outer for loop that goes through each
basket
- An inner loop that goes through every single
fruit
item
Then just print out the fruit
that is not the user's choice
.