Dennis
Dennis

Reputation: 269

Divide certain elements in each sub list

b = [[2021, 55, -0.65, 7.61, 10.65, 41.37, 3.39, 12.25, -10.14, 7.61, 8.84],
     [2022, 56, 3.0, -0.13, 8.84, 27.25, -0.48, 2.54, 12.43, 7.56, 3.37]]

I want to divide elements [2:10] of each sub list in b by 100. Result expected:

a = [2021, 55, -0.0065, 0.0761, 0.1065, 0.4137, 0.0339, 0.1225, -0.1014, 0.0761, 0.0884], etc

I've tried:

a = [item[2:10] /100 for item in b] Also tried: a = [item[2:10] / 100 for item in x] for x in b]

The first one gives "unsupported operand type for /: list and int". Second one gives "int object not subscriptable"

Upvotes: 0

Views: 41

Answers (4)

Ajay D.
Ajay D.

Reputation: 1

res = [x[:2] + [x[i]/100 for i in range(len(x)) if i > 1] for x in b]\
print(res)

Upvotes: 0

Shubham
Shubham

Reputation: 1438

A minor error in your list comprehension, you were slicing in the wrong place. What you need to do is this:

a = [x[:2] + [item / 100 for item in x[2:]] for x in b]
print(a)

Output:

[[2021, 55, -0.006500000000000001, 0.0761, 0.1065, 0.41369999999999996, 0.0339, 0.1225, -0.1014, 0.0761, 0.08839999999999999], [2022, 56, 0.03, -0.0013, 0.08839999999999999, 0.2725, -0.0048, 0.0254, 0.1243, 0.0756, 0.0337]]

Upvotes: 1

S.B
S.B

Reputation: 16486

No need to take slices out first... change your list-comprehension to:

b = [[2021, 55, -0.65, 7.61, 10.65, 41.37, 3.39, 12.25, -10.14, 7.61, 8.84],
     [2022, 56, 3.0, -0.13, 8.84, 27.25, -0.48, 2.54, 12.43, 7.56, 3.37]]

res = [[item / 100 if 2 <= i < 10 else item for i, item in enumerate(lst)] for lst in b]

print(res)

Output:

[[2021, 55, -0.006500000000000001, 0.0761, 0.1065, 0.41369999999999996, 0.0339, 0.1225, -0.1014, 0.0761, 8.84], [2022, 56, 0.03, -0.0013, 0.08839999999999999, 0.2725, -0.0048, 0.0254, 0.1243, 0.0756, 3.37]]

Upvotes: 0

bigbounty
bigbounty

Reputation: 17368

Without list comprehension

In [12]: b = [[2021, 55, -0.65, 7.61, 10.65, 41.37, 3.39, 12.25, -10.14, 7.61, 8
    ...: .84],
    ...:      [2022, 56, 3.0, -0.13, 8.84, 27.25, -0.48, 2.54, 12.43, 7.56, 3.37
    ...: ]]
    ...:

In [13]: for i in range(len(b)):
    ...:     if len(b[i]) >= 10:
    ...:         for j in range(2,10):
    ...:             b[i][j] = b[i][j]/100

output:

[[2021,
  55,
  -0.006500000000000001,
  0.0761,
  0.1065,
  0.41369999999999996,
  0.0339,
  0.1225,
  -0.1014,
  0.0761,
  8.84],
 [2022,
  56,
  0.03,
  -0.0013,
  0.08839999999999999,
  0.2725,
  -0.0048,
  0.0254,
  0.1243,
  0.0756,
  3.37]]

Upvotes: 0

Related Questions