2016-05-12 124 views
1

我想通過嵌套列表進行迭代並對元素進行一些更改。更改它們後,我想將結果保存在同一個嵌套列表中。 例如,我有python操作嵌套列表

text = [['I', 'have', 'a', 'cat'], ['this', 'cat', 'is', 'black'], ['such', 'a', 'nice', 'cat']] 

我想名單略有變化元素的列表。例如:

text = [['I_S', 'have', 'a_A', 'cat'], ['this', 'cat_S', 'is', 'black_A'], ['such', 'a', 'nice', 'cat_S']] 

首先,我遍歷每個列表,然後遍歷列表中的每個項目,然後應用其他代碼進行所需的更改。但是如何在操作之後返回嵌套列表?這是我做的:

for tx in text: 
    for t in tx: 
     #making some operations with each element in the nested list. 
     #using if-statements here 
    result.append() 

什麼我已經得到了所有更改的元素從嵌套列表

result = ['I_S', 'have', 'a_A', 'cat', 'this', 'cat_S', 'is', 'black_A', 'such', 'a', 'nice', 'cat_S'] 

我需要保持嵌套列表,因爲它實際上是句子中的單一列表從文本。

+0

這不是100 %清楚你問的是什麼 - 你想保留原來的列表清單,並返回一個新的,修改後的副本? –

+0

應該很難修改你的內部列表 - 你是否可以包含足夠的代碼來實際複製你的問題? – khelwood

+0

對不起,我想要修改list of list。 –

回答

3

要創建一個嵌套列表作爲輸出試試這個:

result = [] 
for i in range(len(text)): 
    temp = [] 
    for t in text[i]: 
     word_modified = t 
     #making some operations with each element in the nested list. 
     #using if-statements here 
     temp.append(word_modified) 
    result.append(temp) 
result 

如果只是複製粘貼此代碼,result將是等於text。但是在循環中,t代表每個單詞分離,你應該可以隨意修改它。

0
[[item + change if needchange else item for item in lst ] for lst in test ] 

def unc(item): 
    #do something 
    return res 
[[func(item) for item in lst ] for lst in test ] 
1

爲了使您的代碼的可讀性,您可以使用嵌套列表理解創建結果列表,並定義附加額外的字符串,以適當文字的功能。

result_text = [[word_processor(word) for word in word_cluster] for word_cluster in text] 

您函數將是這樣的形式:

def word_processor(word): 
    # use word lengths to determine which word gets extended 
    if len(word) > 1 and isintance(word, str): 
      return word + "_S" 
    else: 
      # Do nothing 
      return word 

功能嚴格取決於你想要達到的目的。

+1

對於其他用戶尋找答案,文字解釋有點長。 –

+0

@LaurIvan謝謝。我已經添加了幾行描述 –

0

可以將嵌套形式的修改後的結果保留在相同的原始列表中。單行代碼將爲此工作。

您可以嘗試簡單:

文本= [ 'I', '有', 'A', '貓'],[ '這個', '貓', '是', '黑' ],[ '這樣', 'A', '好', '貓']

map(lambda x:map(function,x),text) 

而且,您可以按照您的要求寫這樣的函數定義:

def function(word): 
    #modification/Operations on Word 
    return word