問題如下:
撰寫代碼以僅查找串列中以數字 3 結尾的那些數字。將結果存盤在一個名為“output_list”的空串列中。注意:對于這個,您必須將整數轉換為字串并使用索引來查找最后一位數字。
我們有清單:
x = [12,43,4,1,6,343,10, 34, 12, 93, 783, 330, 896, 1, 55]
首先,我嘗試使用 for 回圈將整數轉換為字串資料型別。
output_list = []
for i in x:
output_list.append(str(i))
print(output_list)
輸出是:
['12', '43', '4', '1', '6', '343', '10', '34', '12', '93', '783', '330', '896', '1', '55']
然后,在串列中查找以數字 3 結尾的數字。我正在使用這個 for 回圈來查找以數字 3 結尾的數字,但它不起作用。
for i in output_list:
if(output_list[len(i) -1]=='3'):
print(output_list)
uj5u.com熱心網友回復:
簡單的pythonic一班輪:
x = [12,43,4,1,6,343,10, 34, 12, 93, 783, 330, 896, 1, 55]
output_list = [str(i) for i in x if str(i)[-1]=="3"]
print(output_list) # ['43', '343', '93', '783']
uj5u.com熱心網友回復:
我不知道為什么要求您將整數轉換為字串以實作此目的。當您只需要:
x = [12,43,4,1,6,343,10, 34, 12, 93, 783, 330, 896, 1, 55]
print([v for v in x if v % 10 == 3])
輸出:
[43, 343, 93, 783]
但是,為了完整起見,您可以執行以下操作:
print([v for v in x if str(v)[-1] == '3'])
uj5u.com熱心網友回復:
如果您不需要單線解決方案:
result = []
for i in output_list:
if i[-1] == '3':
result.append(int(i))
print(result)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/429473.html
