0

我有一个列表列表

w = [['2', '22', '32', '44', '55', '66', '69', '94'], ['22', '24', '49', '74', '90', '113', '130', '140']]

必须从中派生一个新的列表列表,其中:even indices will have 1 subtracted from them和处的所有元素all odd indices will have 1 added to them。所以上面的列表看起来像:

x = [['1','23','31','45','54','67','68','93'],['21','25','48','75','89','114','129','141']]

任何帮助将不胜感激。

4

4 回答 4

5
>>> w = [['2', '22', '32', '44', '55', '66', '69', '94'], ['22', '24', '49', '74', '90', '113', '130', '140']]
>>> [[str(int(s)+(1 if i%2 else -1)) for i, s in enumerate(lst)] for lst in w]
[['1', '23', '31', '45', '54', '67', '68', '95'], ['21', '25', '48', '75', '89', '114', '129', '141']]
于 2013-03-26T23:36:00.770 回答
1

已发布带有列表理解的答案。这是使用简单 for 循环的替代方法:

for ls in w:
    for i, v in enumerate(ls):
        if i % 2:
            ls[i] = str(int(v) + 1)
        else:
            ls[i] = str(int(v) - 1)
于 2013-03-26T23:45:54.773 回答
1
于 2013-03-26T23:49:31.740 回答
0

So heres one method:

w = [[str(int(y)+(-1,1)[i%2]) for i,y in enumerate(x)] for x in w]

basically you just iterate over the lists, and then iterate over the elements of each list, adding / subtracting 1 depending on x%2 (odd / even).

Since this is done in a list constructor or two, the lists are rebuilt as they are iterated over.

于 2013-03-26T23:38:05.173 回答