我有一個多維串列,其中的元素包含字串。例如:
list = [['blur', 'ccd', 'damage', 'jack', 'flare', 'reason'],
['jump', 'everyone'],
['sadness', 'sick', 'joy']]
我想將這些字串合并為一個元素。就像是:
list = [['blur ccd damage jack flare reason'],
['jump everyone'],
['sadness sick joy']]
我正在嘗試使用 for 回圈,但出現一些錯誤或意外結果。
uj5u.com熱心網友回復:
簡單的方法是串列理解str.join:
>>> my_list = [['blur', 'ccd', 'damage', 'jack', 'flare', 'reason'],
... ['jump', 'everyone'],
... ['sadness', 'sick', 'joy']]
>>> [' '.join(x) for x in my_list]
['blur ccd damage jack flare reason', 'jump everyone', 'sadness sick joy']
>>> [[' '.join(x)] for x in my_list]
[['blur ccd damage jack flare reason'], ['jump everyone'], ['sadness sick joy']]
uj5u.com熱心網友回復:
你可以使用它:
list = [['blur', 'ccd', 'damage', 'jack', 'flare', 'reason'],
['jump', 'everyone'],
['sadness', 'sick', 'joy']]
for smallerList in list:
combinedWord = ""
for word in smallerList:
combinedWord = word " "
smallerList.clear()
smallerList.append(combinedWord)
# print(smallerList)
print(list)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/398295.html
上一篇:python映射元組串列
下一篇:比較兩個串列并傳遞給另一個
