[英]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'
. 说我有一个列表
['GBP', 31, 'PIT', 25, ['Football]]
但我想对其进行修改,以便所有整数都比原始整数少7,并且所有列表都转换为字符串'Football'
。 I am not really sure how to let python scan through every item in the list, determine their type, and make corresponding changes. 我不太确定如何让python扫描列表中的每个项目,确定其类型,并进行相应的更改。 I tried something like
我尝试了类似的东西
for x in the_list:
if type(x) == ......:
x = .....
but it does not really work... 但这确实不起作用...
Use isinstance()
: 使用
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. 这种方法使您可以灵活地配置转换并使它们紧凑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.