簡體   English   中英

使用整數,float和字符串替換列表上的值而不更改列表結構

[英]replace values on a list with integers, float and strings without changing the list structure

我有這個代碼

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”替換為“早上好”,您可以這樣做:

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塊中包裝整個東西:

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”是一個可怕的變量名稱。 您的行不包含長度為一個字符串,因此它們不是字符。

第一行應該是包含單個整數的列表。 如果你真的不想出於某種原因這樣做,你將不得不將整個事情包裝在另一個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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM