修改嵌套列表元素的最优雅方法 [英] Most elegant way to modify elements of nested lists in place
本文介绍了修改嵌套列表元素的最优雅方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个二维列表,如下所示:
I have a 2D list that looks like this:
table = [['donkey', '2', '1', '0'], ['goat', '5', '3', '2']]
我想将最后三个元素更改为整数,但是下面的代码却很难看:
I want to change the last three elements to integers, but the code below feels very ugly:
for row in table:
for i in range(len(row)-1):
row[i+1] = int(row[i+1])
但是我宁愿有这样的东西:
But I'd rather have something that looks like:
for row in table:
for col in row[1:]:
col = int(col)
我认为应该有一种方法可以编写上面的代码,但是分片创建的迭代器/新列表与原始列表是分开的,因此引用不会继续存在.
I think there should be a way to write the code above, but the slice creates an iterator/new list that's separate from the original, so the references don't carry over.
有没有办法获得更多的Python解决方案?
Is there some way to get a more Pythonic solution?
推荐答案
for row in table:
row[1:] = [int(c) for c in row[1:]]
上面看起来更像Python吗?
Does above look more pythonic?
这篇关于修改嵌套列表元素的最优雅方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文