如何在Python的列表列表中按值替换元素?

时间:2016-10-11 14:58:04

标签: python list replace list-comprehension

我有:

 counts = [[2, 2, 2, 0], [2, 2, 1, 0]]
 countsminusone = [[1, 1, 1, -1], [1, 1, 0, -1]] #Which is counts - 1

对于countminusone为0或小于0的每个值,我想将其替换为1.

 countsminusone1 = [[1 if x == 0 or x < 0 else x for x in pair] for pair in countsminusone] #I cannot get this to work

然后按countminusone划分计数

Divide = [[n/d for n, d in zip(subq, subr)] for subq, subr in zip(counts, countsminusone)] #This should work if the above works

2 个答案:

答案 0 :(得分:2)

我认为你这太复杂了。让我们以最简单的方式说明你真正想做的事情:

  

目标:将列表列表中的每个数字n除以n - 1,如果n - 1 <= 0,则除以1。

这可以在不创建额外列表和压缩的情况下完成:

ContentProvider

请注意,在这种情况下,counts = [[2, 2, 2, 0], [2, 2, 1, 0]] divided = [[i / max(i - 1, 1) for i in sublst] for sublst in counts] 始终为1。

答案 1 :(得分:1)

它有效,但您忘记在最后一行中将countsminusone替换为countsminusone1

countsminusone1 = [[1 if x <= 0 else x for x in pair] for pair in countsminusone]
Divide = [[n/d for n, d in zip(subq, subr)] for subq, subr in zip(counts, countsminusone1)]