lundi 17 mai 2021

Python: change random element from first column of 2D list

I have a list:

ls = [["a", "b"],
      ["c", "d"],
      ["e", "f"]]

I want to change a, c or e to 1. I tried this:

import random

for num, row in enumerate(ls):
    r = random.choice(num[0])
    r[0] = 1
print(ls)

But I only get:

r = random.choice(num[0])
TypeError: 'int' object is not subscriptable

How can I change a random element from the first column of 2D array?




Aucun commentaire:

Enregistrer un commentaire