【问题标题】:Get the characters from a list of lists从列表列表中获取字符
【发布时间】:2015-11-27 11:21:46
【问题描述】:

我有这个例子:

example=[["hello i am adolf","hi my name is "],["this is a test","i like to play"]]

所以,我想得到以下数组:

chars2=[['h', 'e', 'l', 'l', 'o', ' ', 'i', ' ', 'a', 'm', ' ', 'a', 'd', 'o', 'l', 'f','h', 'i', ' ', 'm', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's'],['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', 'i', ' ', 'l', 'i', 'k', 'e', ' ', 't', 'o', ' ', 'p', 'l', 'a', 'y']]

我试过了:

chars2=[]
for list in example:
    for string in list:
        chars2.extend(string)

但我得到以下信息:

['h', 'e', 'l', 'l', 'o', ' ', 'i', ' ', 'a', 'm', ' ', 'a', 'd', 'o', 'l', 'f', 'h', 'i', ' ', 'm', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' ', 't', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', 'i', ' ', 'l', 'i', 'k', 'e', ' ', 't', 'o', ' ', 'p', 'l', 'a', 'y']

【问题讨论】:

    标签: python list chars


    【解决方案1】:

    对于示例中的每个 list,您需要在 chars2 中添加另一个列表,目前您只是直接使用每个字符扩展 chars2。

    例子-

    chars2=[]
    for list in example:
        a = []
        chars2.append(a)
        for string in list:
            a.extend(string)
    

    示例/演示 -

    >>> example=[["hello i am adolf","hi my name is "],["this is a test","i like to play"]]
    >>> chars2=[]
    >>> for list in example:
    ...     a = []
    ...     chars2.append(a)
    ...     for string in list:
    ...         a.extend(string)
    ...
    >>> chars2
    [['h', 'e', 'l', 'l', 'o', ' ', 'i', ' ', 'a', 'm', ' ', 'a', 'd', 'o', 'l', 'f', 'h', 'i', ' ', 'm', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' '], ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', 'i', ' ', 'l', 'i', 'k', 'e', ' ', 't', 'o', ' ', 'p', 'l', 'a', 'y']]
    

    【讨论】:

      【解决方案2】:

      尝试使用简单的列表推导

      example = [list(item) for sub in example for item in sub]
      

      【讨论】:

      • 仅供参考,它没有给出 OP 在 我想要得到以下数组中给出的内容: .
      猜你喜欢
      • 1970-01-01
      • 2022-01-11
      • 2015-03-24
      • 2019-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-08
      相关资源
      最近更新 更多