python 中嵌套列表的操作

operations with nested lists in 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']]

首先,我浏览每个列表,然后浏览列表中的每个项目,然后应用附加代码进行所需的更改。但是如何return操作后返回嵌套列表呢?这就是我所做的:

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分别表示每个单词,所以你应该可以随意修改它。

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

为了使您的代码可读,您可以使用嵌套列表理解来创建结果列表并定义一个函数,将额外的字符串附加到适当的文本。

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

功能完全取决于您要实现的目标。

可以以嵌套形式将修改后的结果保存在相同的原始列表中。单行代码将适用于此。

您可以简单地尝试一下:

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

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

您可以根据需要编写此函数定义,例如:

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