2024-07-06 23:50:30 发布
网友
假设我有一个列表['GBP', 31, 'PIT', 25, ['Football]],但我想修改它,使所有整数都比原始整数少7,并且所有列表都转换为字符串'Football'。我真的不知道如何让python扫描列表中的每一项,确定它们的类型,并做出相应的更改。我试过类似的方法
['GBP', 31, 'PIT', 25, ['Football]]
'Football'
for x in the_list: if type(x) == ......: x = .....
但它并没有真正起作用。。。你知道吗
使用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']
对于一般情况,可以为类型定义转换字典:
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']
这种方法允许您灵活地配置转换并保持它们的紧凑性。你知道吗
使用
isinstance()
:对于一般情况,可以为类型定义转换字典:
这种方法允许您灵活地配置转换并保持它们的紧凑性。你知道吗
相关问题 更多 >
编程相关推荐