如何对列表中的内容类型进行多次更改?

2024-07-06 23:50:30 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个列表['GBP', 31, 'PIT', 25, ['Football]],但我想修改它,使所有整数都比原始整数少7,并且所有列表都转换为字符串'Football'。我真的不知道如何让python扫描列表中的每一项,确定它们的类型,并做出相应的更改。我试过类似的方法

for x in the_list:
  if type(x) == ......:
    x = .....

但它并没有真正起作用。。。你知道吗


Tags: the方法字符串in类型列表forif
2条回答

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

这种方法允许您灵活地配置转换并保持它们的紧凑性。你知道吗

相关问题 更多 >