【问题标题】:How to create list of items in a list by index in python [duplicate]如何在python中按索引创建列表中的项目列表[重复]
【发布时间】:2019-06-06 03:55:36
【问题描述】:

我有一个列表m

m = ['ABC', 'XYZ', 'LMN']

我希望输出如下:

m = [['a','x','l']
     ['b','y','m']
     ['c','z','n']]

如何做到这一点?

【问题讨论】:

标签: python list


【解决方案1】:

使用list(zip(*..))转置嵌套列表,使用列表推导创建嵌套列表:

print(list(zip(*[list(i.lower()) for i in m])))

输出:

[('a', 'x', 'l'), ('b', 'y', 'm'), ('c', 'z', 'n')]

如果希望子值是列表:

print(list(map(list,zip(*[list(i.lower()) for i in m]))))

输出:

[['a', 'x', 'l'], ['b', 'y', 'm'], ['c', 'z', 'n']]

【讨论】:

  • 感谢您的帮助
  • @kalpesh 如果它有效,别忘了接受它:-)
【解决方案2】:

您只需要一个列表理解,zip 用于转置,map 用于转换为更低。

   > m=['ABC','XYZ','LMN']
   > [list(map(str.lower, sub)) for sub in zip(*m)]
   [['a', 'x', 'l'], ['b', 'y', 'm'], ['c', 'z', 'n']]

【讨论】:

  • 不是 OP 想要的输出
  • @U9-转发。哎呀。没有看到转置。谢谢!
  • 大声笑,:-),很高兴你编辑了它。
【解决方案3】:
m=['ABC','XYZ','LMN']
import numpy as np
new_list = [[0, 0, 0], [0, 0,0],[0,0,0]]

j = 0

for i in m:
    a = list(i.lower())
    print(a)
    new_list[j] = a
    j = j+1
np.transpose(new_list).tolist()

输出:

[['a', 'x', 'l'], ['b', 'y', 'm'], ['c', 'z', 'n']]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    • 1970-01-01
    • 2019-09-17
    • 2018-08-20
    • 2019-05-11
    • 2014-07-29
    相关资源
    最近更新 更多