在不改变列表结构的情况下,用整数、浮点数和字符串替换列表中的值

0 投票
1 回答
5684 浏览
提问于 2025-04-17 18:10

我有这段代码

a=[0,['hello','charles', 'hey', 'steve', 'hey', 0.0, 1.5, 23]]  
for row in a:
   for ix, char in enumerate(row):
       if 'hello' in char:
           row[ix] = 'Good Morning'

但是这不管用,因为我在同一个列表里有整数、浮点数和字符串。我需要把“hello”换成“Good Morning”,而且还要保持数据结构和属性的类型,因为我之后会用这些数据做一些数学计算。谢谢!

1 个回答

2

如果你只是想把“Hello”换成“good morning”,你可以直接这样做:

a = [[0], ['hello','charles', 'hey', 'steve', 'hey', 0.0, 1.5, 23]]  
for row in a:
    for index, item in enumerate(row):
        if item == "hello":
            row[index] = "Good morning"

如果你想替换任何包含“hello”的字符串,我建议把整个过程放在一个try except块里,这样可以处理可能出现的错误:

a = [[0], ['hello','charles', 'hey', 'steve', 'hey', 0.0, 1.5, 23]]  
for row in a:
    for index, item in enumerate(row):
        try:
            if "hello" in item:
                row[index] = "Good morning"
        except TypeError:
            pass

顺便说一下,“char”这个变量名不好。你的行里面并不包含长度为1的字符串,所以它们不是字符。

第一行其实应该是一个只包含一个整数的列表。如果你有特别的原因不想这样做,那你就得再把整个过程放在另一个try/except块里:

a = [0, ['hello','charles', 'hey', 'steve', 'hey', 0.0, 1.5, 23]]  
for row in a:
    try:
        for index, item in enumerate(row):
            if item == "hello":
                row[index] = "Good morning"
    except TypeError:
        pass

撰写回答