Reputation: 117
say i have a list ['GBP', 31, 'PIT', 25, ['Football]]
but I would like to modify it so that all integers are 7 less than original and all lists are converted to the string 'Football'
. I am not really sure how to let python scan through every item in the list, determine their type, and make corresponding changes. I tried something like
for x in the_list:
if type(x) == ......:
x = .....
but it does not really work...
Upvotes: 1
Views: 56
Reputation: 886
For the general case, you can define a conversion dictionary for types:
d = {
int:lambda x: x-7,
list:lambda x: x[0]
}
my_list = ['GBP', 31, 'PIT', 25, ['Football']]
new_list = [d.get(type(item), lambda x: x)(item) for item in my_list]
print(new_list) # ['GBP', 24, 'PIT', 18, 'Football']
This approach allows you to flexibly configure conversions and keeps them compact.
Upvotes: 1
Reputation: 21264
Use isinstance()
:
the_list = ['GBP', 31, 'PIT', 25, ['Football']]
for i, x in enumerate(the_list):
if isinstance(x, list):
the_list[i] = 'Football'
elif isinstance(x, int):
the_list[i] = x -7
the_list
['GBP', 24, 'PIT', 18, 'Football']
Upvotes: 1