简体   繁体   中英

How to make multiple changes to contents in a list with regard to their types?

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...

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']

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM