zoukankan      html  css  js  c++  java
  • 在Python中将列表转换为列表

     

    在数据分析期间,我们面临着将列表中的每个元素转换为子列表的方案。因此,在本文中,我们将需要一个普通列表作为输入,并转换成列表列表,其中每个元素都成为一个子列表。

    使用for循环

    这是一种非常简单的方法,其中我们创建了for循环来读取每个元素。我们将其作为列表读取,并将结果存储在新列表中。

    Alist = ['Mon','Tue','Wed','Thu','Fri']
    
    #Given list
    print("Given list: ",Alist)
    
    # Each element as list
    NewList= [[x] for x in Alist]
    
    # Print
    print("The new lists of lists: ",NewList)

    输出量

    运行上面的代码给我们以下结果-

    Given list: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
    The new lists of lists: [['Mon'], ['Tue'], ['Wed'], ['Thu'], ['Fri']]

    使用Split

    在这种方法中,我们使用split函数提取每个用逗号分隔的元素。然后,我们继续将此元素作为列表添加到新创建的列表中。

    Alist = ['Mon','Tue','Wed','Thu','Fri']
    
    #Given list
    print("Given list: ",Alist)
    
    NewList= []
    
    # Using split
    for x in Alist:
       x = x.split(',')
       NewList.append(x)
    
    # Print
    print("The new lists of lists: ",NewList)

    输出量

    运行上面的代码给我们以下结果-

    Given list: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
    The new lists of lists: [['Mon'], ['Tue'], ['Wed'], ['Thu'], ['Fri']]

    使用Map

    映射函数用于将相同的函数一次又一次地应用于一系列参数。因此,我们使用lambda函数通过从原始列表中读取每个元素并将其应用map函数来创建一系列列表元素。

    Alist = ['Mon','Tue','Wed','Thu','Fri']
    
    #Given list
    print("Given list: ",Alist)
    
    # Using map
    NewList= list(map(lambda x:[x], Alist))
    
    # Print
    print("The new lists of lists: ",NewList)

     

    输出量

    运行上面的代码给我们以下结果-

    Given list: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
    The new lists of lists: [['Mon'], ['Tue'], ['Wed'], ['Thu'], ['Fri']]
  • 相关阅读:
    左偏树
    论在Windows下远程连接Ubuntu
    ZOJ 3711 Give Me Your Hand
    SGU 495. Kids and Prizes
    POJ 2151 Check the difficulty of problems
    CodeForces 148D. Bag of mice
    HDU 3631 Shortest Path
    HDU 1869 六度分离
    HDU 2544 最短路
    HDU 3584 Cube
  • 原文地址:https://www.cnblogs.com/a00ium/p/13622404.html
Copyright © 2011-2022 走看看