在Python中制作相同大小的列表

时间:2017-04-11 04:32:38

标签: python arrays list

我有3个不同长度的不同列表。

我想用“X”附加较短的列表,并使大小等于最长列表的长度。

A = [10,20,30,40,50]
B = ["A", "B", "C"]
C = ["X1", "X2"]

追加“X”后,它应如下所示:

A = [10,20,30,40,50]
B = ["A", "B", "C", "X","X"]
C = ["P1", "P2", "X", "X", "X"]

我已使用以下代码实现它,

for i, a in enumerate(A):
    if i < len(B):
        ;
    else:
        B.append('X')

我怎么能在python中有效地做到这一点?

5 个答案:

答案 0 :(得分:5)

使用extend方法

B.extend(['X'] * (len(A)-len(B)))

答案 1 :(得分:2)

为您制作此功能的写入功能

A = [10, 20, 30, 40, 50]
B = ["A", "B", "C"]
C = ["X1", "X2"]


def extend_with_extra_elements(*some_lists):
    max_some_lists_length = max(map(len, some_lists))
    for some_list in some_lists:
        extra_elements_count = max_some_lists_length - len(some_list)
        extra_elements = ['X'] * extra_elements_count
        yield some_list + extra_elements


A, B, C = extend_with_extra_elements(A, B, C)

足够有效

答案 2 :(得分:1)

计算最大长度,并为每个列表附加增量。

在Python中,List有一个二元运算符+可以将多个列表连接在一起,而*则可以自我整理。

A = [10,20,30,40,50]
B = ["A", "B", "C"]
C = ["X1", "X2"]
max_length = max(max(len(A), len(B)), len(C))
A += ['X'] * (max_length - len(A))
B += ['X'] * (max_length - len(B))
C += ['X'] * (max_length - len(C))

然后使用容器列表组织它们,以减少重复的代码和更好的可扩展性。

A = [10,20,30,40,50]
B = ["A", "B", "C"]
C = ["X1", "X2"]

arrays = [A, B, C]
max_length = 0
for array in arrays:
    max_length = max(max_length, len(array))

for array in arrays:
    array += ['X'] * (max_length - len(array))

结果:

print(A) # [10, 20, 30, 40, 50]
print(B) # ['A', 'B', 'C', 'X', 'X']
print(C) # ['X1', 'X2', 'X', 'X', 'X']

答案 3 :(得分:1)

python itertools模块有很多漂亮的功能,对于这样的情况很有用。例如:

>>> from itertools import izip_longest, izip
>>> A = [10, 20, 30, 40, 50]
>>> B = ["A", "B", "C"]
>>> C = ["X1", "X2"]
>>> A, B, C = (list(x) for x in (izip(*izip_longest(A, B, C, fillvalue='X'))))
>>> A
[10, 20, 30, 40, 50]
>>> B
['A', 'B', 'C', 'X', 'X']
>>> C
['X1', 'X2', 'X', 'X', 'X']

答案 4 :(得分:0)

尝试使用max()获取最大长度,然后将列表附加到BC

如果您想将X替换为P,可以使用列表推导[i.replace('X','P') for i in C]来获取['P1','P2']

>>> m=max(len(A),len(B),len(C))
>>> B+['X']*(m-len(B))
['A', 'B', 'C', 'X', 'X']
>>> [i.replace('X','P') for i in C]+['X']*(m-len(C))
['P1', 'P2', 'X', 'X', 'X']