'How do I find find the index of the greatest integer in a list that contains integers and strings in Python?
Thats how the list looks like
incomes = ['Kozlowski', 52000, 'Kasprzak', 51000, 'Kowalski', 26000]
I want to print the biggest income and the surname of the person with that income (index of the income - 1)
Solution 1:[1]
You can try this:
index_of_highest_salary = incomes.index(np.max(incomes[1::2]))
Solution 2:[2]
You can create a dict from your data, then use max to find the key with the largest corresponding value.
>>> incomes = ['Kozlowski', 52000, 'Kasprzak', 51000, 'Kowalski', 26000]
>>> data = dict(zip(incomes[::2], incomes[1::2]))
>>> data
{'Kozlowski': 52000, 'Kasprzak': 51000, 'Kowalski': 26000}
>>> max(data.items(), key=lambda i: i[1])
('Kozlowski', 52000)
Then you don't need indexing and the data is more structured.
Solution 3:[3]
Your title question is different to what you're asking, so here's an answer for your title: If you don't want to use other libraries like numpy, you can do this:
index = 0
max_n = None
for i in range(len(incomes)):
element = incomes[i]
if type(element) == int or type(element) == float:
if max_n is None or element > max_n:
max_n = element
index = i
index will hold the index of the largest number of the list.
Solution 4:[4]
This answer assumes you want the index of the entry as stated in the title of your question.
Use enumerate to create data where index and value are combined.
incomes = ['Kozlowski', 52000, 'Kasprzak', 51000, 'Kowalski', 26000]
print(list(enumerate(incomes[1::2])))
This will give you [(0, 52000), (1, 51000), (2, 126000)].
We can now feed this data to max and use a key function that gives us the second entry of each tuple. When we get this tuple we can get the index from the first entry in the tuple. Since we left out every second element (the name) this index must be multiplied by 2.
incomes = ['Kozlowski', 52000, 'Kasprzak', 51000, 'Kowalski', 26000]
max_income = max(enumerate(incomes[1::2]), key=lambda x: x[1])
print(max_income[0] * 2)
If you want the index and the entries the code can be adjusted.
max_income = max(enumerate(zip(incomes[::2], incomes[1::2])), key=lambda x: x[1][1])
print(max_income)
This will give you a tuple with an index as the first entry and a tuple with name and income as the second entry. To map this index to your incomes list it will have to be multiplied by 2.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sajal Randhar |
| Solution 2 | Cory Kramer |
| Solution 3 | Konny |
| Solution 4 |
