【问题标题】:How to convert list of ints into list of lists?如何将整数列表转换为列表列表?
【发布时间】:2016-12-16 15:11:27
【问题描述】:

问题是:如何正确地(以“pythonic 方式”)将整数列表:[1, 3, 7, 6] 转换为相应的列表列表:[[1], [3], [7], [6]],其中包含整数?

尝试这样做:unsorted_list = [list(str(x)) for x in unsorted_list] 但得到[['1'], ['3'], ['7'], ['6']]。不知道如何在整数上执行相同的操作,它们不可迭代。之后使用for 可以解决问题,但不是那么优雅。 谢谢。

【问题讨论】:

  • @metatoaster 这样就可以了,谢谢。
  • unsorted_list = [[x] for x in unsorted_list]

标签: python list


【解决方案1】:

您不应该将整数转换为字符串。简单地说:

[[x] for x in unsorted_list]

【讨论】:

  • 谢谢,看起来很合乎逻辑
【解决方案2】:

另一种方法,使用map

map(lambda x: [x], unsorted_list)

【讨论】:

    【解决方案3】:

    我们喜欢这样

    unsorted_list = [[x] for x in unsorted_list]
    

    或者你可以使用:

    unsorted_list = map(lambda x:[x], unsorted_list)
    

    【讨论】:

    • 同样的事情:TypeError: 'int' object is not iterable.
    猜你喜欢
    • 1970-01-01
    • 2018-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 2022-11-10
    相关资源
    最近更新 更多