如何从列表和整数输出2d列表

时间:2016-03-03 23:12:21

标签: python

我正在尝试编写一个以输入列表和两个整数作为参数的函数,然后该函数返回一个二维列表,列表的行和列由两个输入整数指定。例如如果输入列表是[8, 2, 9, 4, 1, 6, 7, 8, 7, 10]且两个整数是2和3,那么函数应该返回[[8, 2, 9],[4, 1, 6]]

def one_to_2D(some_list, r, c):
    output = []

    for a in range(0, r):
        my_list = some_list[0:c]
        some_list.reverse()
        for k in range(0,r):
            some_list.pop()
        some_list.reverse()
        output.append(my_list)

    return output

some_list = [8, 2, 9, 4, 1, 6, 7, 8, 7, 10]
print(one_to_2D(some_list, 2, 3))

8 个答案:

答案 0 :(得分:1)

以下是您的解决方案:

def one_to_2D(some_list, r, c):
    return [[some_list[j] for j in range(c*i, c*(i+1))] for i in range(r)]

示例:

In [3]: one_to_2D([8, 2, 9, 4, 1, 6, 7, 8, 7, 10], 2, 3)
Out[3]: [[8, 2, 9], [4, 1, 6]]

In [4]: one_to_2D([8, 2, 9, 4, 1, 6, 7, 8, 7, 10], 3, 3)
Out[4]: [[8, 2, 9], [4, 1, 6], [7, 8, 7]]

In [5]: one_to_2D([8, 2, 9, 4, 1, 6, 7, 8, 7, 10], 2, 2)
Out[5]: [[8, 2], [9, 4]]

答案 1 :(得分:0)

这是一个带有for循环和Python的切片表示法的简单解决方案:

def one_to_2D(some_list, r, c):
    result = []
    for i in range(1, r+1):
        result.append(some_list[c*(i-1):c*i])
    return result

print(one_to_2D([8, 2, 9, 4, 1, 6, 7, 8, 7, 10], 2, 3))

输出:

[[8, 2, 9], [4, 1, 6]]

答案 2 :(得分:0)

你可以使用列表理解,它通常比扩展的for循环版本更快:

def one_to_2D(some_list, r, c):
    return [some_list[i:i+c] for i in range(0, len(some_list), c][:r]

答案 3 :(得分:0)

如果行和列整数的乘积等于列表的长度,那么您可以将列表转换为numpy数组并重新整形:

import numpy as np
>>> list = [8, 2, 9, 4, 1, 6, 7, 8, 7, 10]
>>> np.array(list).reshape(5, 2)
array([[ 8,  2],
   [ 9,  4],
   [ 1,  6],
   [ 7,  8],
   [ 7, 10]])

在您的示例中,您选择的整数是2,3,这是一个比列表长度小的矩阵。您可以编写一个简单的函数来切割列表以适合矩阵的维度:

def one_to_2D(arr, r, c):
    if len(arr) > r * c:
        new_arr = arr[:-(len(arr)-r*c)]
        return np.array(new_arr).reshape(r, c)
    elif len(arr) < r * c:
        print 'list length less than r x c'
    else:
        return np.array(arr).reshape(r,c)

答案 4 :(得分:0)

您可以在列表中使用itertools.islice来电iter

from itertools import islice
def one_to_2D(some_list, r, c):
    it = iter(some_list)
    return [list(islice(it, c)) for _ in range(r)]

输出:

In [15]: (one_to_2D(some_list, 2, 3)
   ....: )
Out[15]: [[8, 2, 9], [4, 1, 6]]

In [16]: (one_to_2D(some_list, 2, 2))
Out[16]: [[8, 2], [9, 4]]

In [17]: (one_to_2D(some_list, 2, 4))
Out[17]: [[8, 2, 9, 4], [1, 6, 7, 8]]

基于如果输入列表中的元素数量大于rc,则忽略额外的元素。如果输入列表中的元素数小于r乘以c然后用关键字None 填充二维列表,则需要填充无:

def one_to_2D(some_list, r, c):
    if r * c > len(some_list):
        some_list.extend([None] * (r * c - len(some_list)) )
    it = iter(some_list)
    return [list(islice(it, c)) for _ in range(r)]

输出:

In [19]: (one_to_2D(some_list, 2, 4))
Out[19]: [[8, 2, 9, 4], [1, 6, 7, 8]]

In [20]: (one_to_2D(some_list, 2, 6))
Out[20]: [[8, 2, 9, 4, 1, 6], [7, 8, 7, 10, None, None]]

如果你必须使用常规循环:

def one_to_2D(some_list, r, c):
    if r * c > len(some_list):
        some_list.extend([None] * (r * c - len(some_list)))
    l = []
    for i in range(0, r * c, c):
        l.append(some_list[i:i + c])
    return l

答案 5 :(得分:0)

In [10]: reshaped = [some_list[i:i+c] for i in range(0,r*c, c)]
[[8, 2, 9], [4, 1, 6]]

答案 6 :(得分:0)

# Function inputs  : a list and two integers --> r, c
# Function output  : a 2D_list by r*c shape

def one_to_2D(some_list, r, c):
    # If the number of elements in the input list
    # is larger than rc then ignore the extra elements.
    # If the number of elements in the input list
    # is less than rc then fill the two dimensional list
    # with the keyword None, we need to pad with None:
    if r*c > len(some_list):
        some_list.extend([None] * (r*c - len(some_list)))
    #print (some_list)

    # This list will contains 
    # the number of r in the list elements.
    # It then extends these elements to the _2D_list
    # after completing the internal loop once.
    result = []

    # Will contain those items that extended into _2D_list from result
    _2D_list = [] 

    for i in range(r):  # 0 <= i < r
        for j in range(i*c, (i+1)*c):
            # i*c <= j < (i+1)*c
            ## i == 0 ===> 0  <= j < c
            ## i == 1 ===> c  <= j < 2c
            ## i == 2 ===> 2c <= j < 3c
            ## ...
            ## ...
            ## i == r ===> break
            result.append(some_list[j])
        _2D_list.extend([result])
        result = []
        # After completing one step of the inner loop,
        # the result items must be deleted by result = [].
        # Because otherwise they will go to the exit(out).

    return _2D_list

    # This function simply with list comprehension ...
    #return [[some_list[j] for j in range(c*i, c*(i+1))] for i in range(r)]

##########################################################
##### Main Program  #####
some_list = [8, 2, 9, 4, 5]
print (one_to_2D(some_list, 3, 4))

答案 7 :(得分:-1)

希望这会有所帮助:

def one_to_2D(some_list, r, c):

    output = []
    if r*c > len(some_list):
        return None

    for i in range(r):
        tl = []
        for j in range(c):
            tl.append(some_list[i*c+j])
        output.append(tl)

    return output

some_list = [8, 2, 9, 4, 1, 6, 7, 8, 7, 10]
print(one_to_2D(some_list, 2, 3))