5 回答

TA貢獻1752條經(jīng)驗 獲得超4個贊
您遇到了字符串格式化問題,因為您正在將字符串 '*' 插入到您已經(jīng)迭代的列表中,位于 i 的下一個索引處。您不能讓字符串執(zhí)行模運算。不完全確定你想在那里做什么,但你看到的是正常行為。
此外,按照您的代碼當前的工作方式,您將無法達到原始列表中的所有整數(shù)。
編輯:回應(yīng)您的編輯:
x_list = ' '.join(str(x)).split()
for i in range(len(x_list)):
if x_list[i] != '*':
if (int(x_list[i]) % 2 == 0) and (int(x_list[i+1]) % 2 == 0):
x_list.insert(i+1,'*')
只需將字符串更改為 int 并檢查 i 處的值是否為“*”

TA貢獻2041條經(jīng)驗 獲得超4個贊
警告說明
在循環(huán)時修改列表并不是可取的。
一些解釋
發(fā)生的情況是,該行x_list[i] % 2
被解釋為格式化字符串的指令,因為最初x_list
包含字符串。
%
目前,在 Python 3 上,不推薦使用格式化。
緩解措施
注意:這解決了格式錯誤,與功能相關(guān)的其他邏輯錯誤可能仍然存在。
x = int('12234')
x_list = ' '.join(str(x)).split()
# Going from indices 0...(N-1) as we use (i+1) each iteration
for i in range(len(x_list)-1):
? ? # Validating current and next are not invalid char '*'
? ? if '*' in [x_list[i], x_list[i+1]]:
? ? ? ? continue
? ? if int(x_list[i])% 2 == 0? and int(x_list[i+1])% 2 == 0 :
? ? ? ? x_list.insert(i+1,'*')
# ['1', '2', '*', '2', '3', '4']
print(x_list)

TA貢獻1812條經(jīng)驗 獲得超5個贊
如果您x_list
包含字符串,那么您顯然無法計算該字符串除以 2 的余數(shù)。
另外,即使您x_list
只包含數(shù)字,您也可能會遇到IndexError
,因為在最后一次迭代中x_list[i+1]
可能超出范圍。
您還在循環(huán)遍歷同一列表時修改了該列表,這通常是不可取的。

TA貢獻1772條經(jīng)驗 獲得超8個贊
x = input()
x_list = ' '.join(str(x)).split()
for i in range(len(x_list)):
try:
if not(int(x_list[i]) % 2 and int(x_list[i+1]) % 2):
x_list.insert(i+1,'*')
except:
continue
print(x_list)
嘗試一下這個,它可能會起作用。我不知道輸出應(yīng)該是什么樣的“因為你沒有提到它”。但我嘗試輸入相同的代碼并進行一些更改以避免錯誤

TA貢獻1827條經(jīng)驗 獲得超8個贊
str
您轉(zhuǎn)換為of chars 的方式list
不正確,可以輕松地用list(string)
.?如果您想檢查所有字符是否為有效數(shù)字,您可以添加str.isdecimal()
.
您試圖修改正在迭代的列表,這也是一個錯誤。修改循環(huán)內(nèi)的源代碼會破壞循環(huán)邏輯,因此某些元素可能會被處理多次或被跳過。
最后,您嘗試在 上應(yīng)用模(即數(shù)字運算)str
。為了讓它按您的預(yù)期工作,您應(yīng)該將 element 轉(zhuǎn)換為int
using?int(string)
。
編輯后的代碼:
x = input()
if x.isdecimal():
? ? x_list = list(x)
? ? new_list = []
? ? for i in range(len(x_list) - 1):
? ? ? ? new_list.append(x_list[i])
? ? ? ? if not (int(x_list[i]) % 2 and int(x_list[i + 1]) % 2):
? ? ? ? ? ? new_list.append("*")
添加回答
舉報