【问题标题】:How to make a list of lists in Python?如何在 Python 中制作列表列表?
【发布时间】:2017-01-17 22:53:17
【问题描述】:

假设,

range(len(column)) = 4
column = ['AAA', 'CTC', 'GTC', 'TTC']
for i in range(len(column)):
    a = list(column[i])

在这个循环之外,我想要一个变量,比如 x 被分配,以便它给出以下输出。

 ['A', 'A', 'A']
 ['C', 'T', 'C']
 ['G', 'T', 'C']
 ['T', 'T', 'C']

完成此操作后,我应该能够执行以下操作: 接下来,我想在 x 内进行比较。说 x[2] 告诉我“G”是否与“T”不同,“G”是否与“C”不同,“T”是否与“C”不同

【问题讨论】:

    标签: python python-2.7 for-loop return


    【解决方案1】:

    我相信您需要一个列表列表

    代码:

    column = ['AAA', 'CTC', 'GTC', 'TTC']
    x=[]
    for i in range(len(column)):
        a = list(column[i])
        x.append(a)
    
    print x
    

    输出:

    [['A', 'A', 'A'], ['C', 'T', 'C'], ['G', 'T', 'C'], ['T', 'T', 'C']]
    

    【讨论】:

      【解决方案2】:

      当你格式化你的数据后你想要做什么样的比较并不完全清楚,但这是一些事情

      import numpy as np
      
      alt_col = [list(y) for y in column]
      x = np.asarray(alt_col)
      

      然后你可以在数组中比较你想要的任何东西

      print all(x[1, :] == x[2, :])
      

      【讨论】:

        【解决方案3】:

        您无需使用numpy 或其他外部模块即可轻松创建x

        column = ['AAA', 'CTC', 'GTC', 'TTC']
        x = [list(column[i]) for i in range(len(column))]
        print(x)
        

        输出:

        [['A', 'A', 'A'], ['C', 'T', 'C'], ['G', 'T', 'C'], ['T', 'T', 'C']]
        

        要使用它,您需要两个索引:您可以将其视为第一个表示行,第二个表示列。例如'G'x[2][0] 中。您可以使用相同的符号将其与 x 中的任何其他单元格进行比较。

        【讨论】:

          【解决方案4】:
          inputs = ['ABC','DEF','GHI'] # list of inputs
          outputs = [] # creates an empty list to be populated
          for i in range(len(inputs)): # steps through each item in the list
              outputs.append([]) # adds a list into the output list, this is done for each item in the input list
              for j in range(len(inputs[i])): # steps through each character in the strings in the input list
                  outputs[i].append(inputs[i][j]) # adds the character to the [i] position in the output list
          
          outputs
          [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]
          

          编辑 添加了关于每行在做什么的 cmets

          【讨论】:

          • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。不鼓励仅使用代码回答。
          猜你喜欢
          • 1970-01-01
          • 2013-10-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-11-08
          • 2017-01-12
          • 1970-01-01
          • 2013-04-22
          相关资源
          最近更新 更多