亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

列表、轉換 Str 列表、替換值、打印新的 str 列表。

列表、轉換 Str 列表、替換值、打印新的 str 列表。

開滿天機 2023-12-26 15:16:49
你們中的任何人都可以幫助我確定我做錯了什么嗎?我知道這可能很簡單,但我對編程和 Python 很陌生。我需要返回['*', '2', '3', '*', '5']。相反,我在列表中獲得了更多的值。測試替換列表中的值repl_list = [1, 2, 3, 1, 5]str_repl_list = str(repl_list)# print('This is the list to replace: ' + str_repl_list)# print(type(str_repl_list[0]))new_str_list = []`enter code here`print(new_str_list)for item in str_repl_list:    replacement = item.replace('1', '*')    new_str_list.append(replacement)    for index, char in enumerate(new_str_list):        print(index, char) # This is to identify what information is being taken as par of the new list
查看完整描述

3 回答

?
隔江千里

TA貢獻1906條經驗 獲得超10個贊

當你執行 a 時str(repl_list),輸出是一個 string '[1, 2, 3, 1, 5]',而不是字符串列表,所以如果你迭代str_repl_list你會得到


1

,

 

2

,

 

3

,

 

1

,

 

5

]

相反,您可以避免該步驟并將每個項目轉換為 for 循環內的字符串 ( str(item) )


repl_list = [1, 2, 3, 1, 5]

new_str_list = []

for item in repl_list:

  replacement = str(item).replace('1', '*')

  new_str_list.append(replacement)


>>> print(new_str_list)

>>> ['*', '2', '3', '*', '5']

您還可以使用列表理解


>>> print(['*' if x == 1 else str(x) for x in repl_list])

>>> ['*', '2', '3', '*', '5']


查看完整回答
反對 回復 2023-12-26
?
慕尼黑的夜晚無繁華

TA貢獻1864條經驗 獲得超6個贊

您不是將每個項目轉換為字符串,而是將整個列表轉換為字符串。相反,嘗試這個列表理解:

str_repl_list = [str(i) for i in str_list]

這將遍歷每個項目并將其轉換為字符串,然后將其存儲在新列表中。


查看完整回答
反對 回復 2023-12-26
?
瀟湘沐

TA貢獻1816條經驗 獲得超6個贊

由于您要附加列表中的每個元素new_str_list,為了查看所需的結果,您需要將它們打印在一起,因此您需要將它們連接到一個字符串中,然后添加字符串中的所有元素。

因此要看到所需的結果,您只需將所有元素添加在一起

可以這樣做

str_list_final = ''.join(new_str_list)


查看完整回答
反對 回復 2023-12-26
  • 3 回答
  • 0 關注
  • 191 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號