我正在嘗試計算字串串列中每個字串的位數:
['', '', '000000000100111101', '', '', '0000112112111101011100000000001', '', '', '', '', '',]
所以我想得到的預期輸出是
[0 0 18 0 0 31 0 0 0 0 0]
我正在考慮使用 numpy 計數,但字串串列的資料型別是串列,所以我應該使用 len 嗎?
我將非常感謝任何人的幫助,謝謝。
uj5u.com熱心網友回復:
將串列推導與len()函式一起使用:
inp = ['', '', '000000000100111101', '', '', '0000112112111101011100000000001', '', '', '', '', '',]
lengths = [len(x) for x in inp]
print(lengths) # [0, 0, 18, 0, 0, 31, 0, 0, 0, 0, 0]
uj5u.com熱心網友回復:
使用 map 函式將內置的 len 函式應用于串列中的每個數字,然后將 map 物件轉換為串列。
nums = ['', '', '000000000100111101', '', '', '0000112112111101011100000000001', '', '', '', '', '',]
lengths = list(map(len, nums))
print(lengths)
輸出:
[0 0 18 0 0 31 0 0 0 0 0]
uj5u.com熱心網友回復:
使用 len() 函式和 for 回圈來獲取串列中每個字串的計數。像這樣
newList = []
for value in values:
newList.append(len(value))
輸出:
[0, 0, 18, 0, 0, 31, 0, 0, 0, 0, 0]
如果你想要不帶逗號的輸出,你想添加一些這樣的陳述句!
anotherList = []
for value in values:
try:
if anotherList[0] != "":
anotherList[0] = str(anotherList[0]) " " str(len(value))
except IndexError:
anotherList.append(len(value))
輸出:
[0 0 18 0 0 31 0 0 0 0 0]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/471054.html
