Skip to main content
 首页 » 编程设计

python之python中嵌套列表的操作

2025年05月04日25JeffreyZhao

我正在尝试遍历嵌套列表并对元素进行一些更改。更改它们后,我想将结果保存在同一个嵌套列表中。 例如,我有

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'] 

我需要保留嵌套列表,因为它实际上是文本中的句子。

请您参考如下方法:

要创建一个嵌套列表作为输出试试这个:

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 分别表示每个单词,因此您应该能够根据需要修改它。