![](/img/trans.png)
[英]How to make List in python dataclass that can accept multiple different types?
[英]How to make multiple changes to contents in a list with regard to their types?
说我有一个列表['GBP', 31, 'PIT', 25, ['Football]]
但我想对其进行修改,以便所有整数都比原始整数少7,并且所有列表都转换为字符串'Football'
。 我不太确定如何让python扫描列表中的每个项目,确定其类型,并进行相应的更改。 我尝试了类似的东西
for x in the_list:
if type(x) == ......:
x = .....
但这确实不起作用...
使用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']
对于一般情况,您可以为类型定义转换字典:
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']
这种方法使您可以灵活地配置转换并使它们紧凑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.