我有這樣的元組的列表:Python的修改列表內的元組
myList=[(u"hell world", 10),(u"hello mom", 20), (u"hello dad","5")]
我需要修改每個元組,以得到類似下面的列表:
mySecondList= [(u"hell",u"world","10"),(u"hello",u"mom","20"), (u"hello",u"dad","5")]
哪有我這麼做?
我有這樣的元組的列表:Python的修改列表內的元組
myList=[(u"hell world", 10),(u"hello mom", 20), (u"hello dad","5")]
我需要修改每個元組,以得到類似下面的列表:
mySecondList= [(u"hell",u"world","10"),(u"hello",u"mom","20"), (u"hello",u"dad","5")]
哪有我這麼做?
正如我在我的評論的元組寫的是不可改變的,但你可以使用類似下面的代碼:
def modify(lst):
ret = []
for tpl in lst:
ret.append(tuple([tpl[0].split(' '), tpl[1]]))
return ret
或者你可以使用一臺發電機,並把它傳遞給tuple
構造:
new_list = tuple(item[0].split(' ') + [item[1]]) for item in myData)
元組是不可變的,所以您需要返回帶有新元組的列表。 – Tobias
發佈您的嘗試.. –
嘗試使用字符串'.split'方法。如果您遇到問題,請發佈您的代碼並準確解釋它做錯了什麼。 –