【问题标题】:Convert list of strings into list of lists with each element in list of lists as each iterable letter in string. All in one line将字符串列表转换为列表列表,列表列表中的每个元素作为字符串中的每个可迭代字母。一条龙
【发布时间】:2015-05-15 03:16:18
【问题描述】:

带有字符串 x 的列表:

x = ['foo', 'bar']

如何在一行中完成以下操作?

y = []
for word in x:
    y.append([n for n in word])
print y

导致:

[['f', 'o', 'o'], ['b', 'a', 'r']]

【问题讨论】:

    标签: python list python-2.7


    【解决方案1】:

    使用list 和简单的列表理解:

    >>> x = ['foo', 'bar']
    >>> y = [list(word) for word in x]
    >>> y
    [['f', 'o', 'o'], ['b', 'a', 'r']]
    

    或将maplist 一起使用:

    >>> y = map(list, x)
    >>> y
    [['f', 'o', 'o'], ['b', 'a', 'r']]
    

    【讨论】:

      【解决方案2】:

      您可以从列表解析中的每个字符串创建list

      >>> x = ['foo', 'bar']
      >>> [list(i) for i in x]
      [['f', 'o', 'o'], ['b', 'a', 'r']]
      

      【讨论】:

        【解决方案3】:
        >>> map(list, ['foo', 'bar'])
        [['f', 'o', 'o'], ['b', 'a', 'r']]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-01-19
          • 1970-01-01
          • 2023-04-07
          • 1970-01-01
          • 2012-10-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多