【问题标题】:Is there a way to iterate through a nested list's items and produce another nested list in Python?有没有办法遍历嵌套列表的项目并在 Python 中生成另一个嵌套列表?
【发布时间】:2016-01-19 18:24:02
【问题描述】:

我正在尝试编写将嵌套的字符列表转换为 unicode 的代码。

 LetterList=[["a", "b", "c","d"],["e","f","g"]]

 ArrayTranslate=[]

 def Encode(Array):
    for List in Array:
        for letter in List:
            if isinstance(letter,int)==False:
               ArrayTranslate.append(ord(letter))
            elif isinstance(letter,int)==True:
               ArrayTransLate.append(letter)
Encode(LetterList)

print(ArrayTranslate)

当我运行程序时,我会生成如下列表

[97, 98, 99, 100, 101, 102, 103]

但是,我想生成这些值的嵌套列表,如下所示: [[97,98,99,100],[101,102,103]] 谁能告诉我我做错了什么或者我想要实现的目标是否可行

【问题讨论】:

    标签: python function python-3.x


    【解决方案1】:

    您的代码不起作用,因为您将结果附加到一个列表中,并且您在最后一个列表中获得了您的值。 您可以使用嵌套的 list comprehension 来做到这一点:

    In [69]: LetterList
    Out[69]: [['a', 'b', 'c', 'd'], [1, 'f', 'g']]
    
    In [70]: [[ord(i) if not isinstance(i, int) else i for i in l] for l in LetterList]
    Out[70]: [[97, 98, 99, 100], [1, 102, 103]]
    

    【讨论】:

      【解决方案2】:

      我刚刚解决了这个问题

      LetterList=[["a", "b", "c","d"],["e","f","g"]]
      
      
      Encode=[[ord(letter) for letter in List] for List in LetterList]
      print(Encode)
      

      这给出了:

       [[97, 98, 99, 100], [101, 102, 103]]
      

      【讨论】:

      • 如果您的LetterList 中有int 将无法正常工作,请尝试我编辑的答案
      • 谢谢,我没有考虑整数
      猜你喜欢
      • 2017-05-27
      • 2021-10-30
      • 2012-11-11
      • 2019-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多