2016-05-12 129 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