Ella
Ella

Reputation: 361

How do I shorten a two-dimensional list?

I have two lists l1 and l2. L2 contains many more values ​​than l1. I would like to adapt it so that l1 and l2 have the same number of values. For example, l1 has 3 entries in the first element. l2 has 8 entries. I would like to bring l2 to the length of l1.

How do I do that better than my solution?

The example below explains it better.

l1 = [[285, 2286, 260], [285, 3614], [671, 3883, 285,85]]
l2 = [[1,2,3,4,5,6,7,8],[1,2,3,4,5,6,7,8], [1,2,3,4,5,6,7,8]]

l3 = [[1,2,3],[1,2], [1,2,3,4]] # What I want

# My try, 
l2_2 = []
for value1, value2 in zip(l1,l2):
length = len(value1)
value2 = value2[:length]
print(value2)
l2_2.append(value2)
  
l2 = l2_2
print(l2)

>>> [1, 2, 3]
>>> [1, 2]
>>> [1, 2, 3, 4]
>>> [[1, 2, 3], [1, 2], [1, 2, 3, 4]]

Upvotes: 1

Views: 47

Answers (2)

Vishnudev Krishnadas
Vishnudev Krishnadas

Reputation: 10960

You don't need to zip the lists, Simple list comprehension would be,

l3 = [l2[i][:len(l)] for i, l in enumerate(l1)]

Output

[[1, 2, 3], [1, 2], [1, 2, 3, 4]]

Upvotes: 1

AKX
AKX

Reputation: 169042

Slice the 1, 2, 3 list with the length of the other list.

l1 = [
    [285, 2286, 260],
    [285, 3614],
    [671, 3883, 285, 85],
]
l2 = [
    [1, 2, 3, 4, 5, 6, 7, 8],
    [1, 2, 3, 4, 5, 6, 7, 8],
    [1, 2, 3, 4, 5, 6, 7, 8],
]
l3 = [k2[: len(k1)] for k1, k2 in zip(l1, l2)]

l3 will be

[[1, 2, 3], [1, 2], [1, 2, 3, 4]]

as expected.

Upvotes: 3

Related Questions