Most elegant way to modify elements of nested lists in place

前端 未结 7 733
囚心锁ツ
囚心锁ツ 2020-12-14 01:20

I have a 2D list that looks like this:

table = [[\'donkey\', \'2\', \'1\', \'0\'], [\'goat\', \'5\', \'3\', \'2\']]

I want to change the la

7条回答
  •  情歌与酒
    2020-12-14 01:40

    I like Shekhar answer a lot.

    As a general rule, when writing Python code, if you find yourself writing for i in range(len(somelist)), you're doing it wrong:

    • try enumerate if you have a single list
    • try zip or itertools.izip if you have 2 or more lists you want to iterate on in parallel

    In your case, the first column is different so you cannot elegantly use enumerate:

    for row in table:
        for i, val in enumerate(row):
            if i == 0: continue
            row[i] = int(val)
    

提交回复
热议问题