【问题标题】:operations with nested lists in pythonpython中嵌套列表的操作
【发布时间】:2016-05-12 12:55:08
【问题描述】:

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

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

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

【问题讨论】:

  • 您的要求并不是 100% 清楚 - 您是否要保留原始列表并返回一个新的、修改后的副本?
  • 在适当的位置修改您的内部列表应该很困难 - 您能否包含足够的代码来实际复制您的问题?
  • 对不起,我想得到修改后的列表。

标签: python list nested nested-loops


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:
    [[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 ]
    

    【讨论】:

      【解决方案3】:

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

      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
      

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

      【讨论】:

      • 一些文字解释对于寻找答案的其他用户大有帮助。
      • @LaurIvan 谢谢。我添加了几行描述
      【解决方案4】:

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

      你可以试试:

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

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

      您可以根据自己的要求编写此函数定义,例如:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-28
        • 2019-12-25
        • 2015-12-02
        • 1970-01-01
        • 2021-01-20
        • 1970-01-01
        • 1970-01-01
        • 2011-07-10
        相关资源
        最近更新 更多