我有一个数字列表如下:
select avg(c),count(c) from (select generate_series(1,10) union select null) as a(c);
我必须按如下方式更改数字:
select
avg(c),
count(c) count_column,
count(*) count_star,
sum(c),
array_agg(c)
from (
select generate_series(1,10) union select null order by 1
) as a(c);
avg | count_column | count_star | sum | array_agg
--------------------+--------------+------------+-----+-----------------------------
5.5000000000000000 | 10 | 11 | 55 | {1,2,3,4,5,6,7,8,9,10,NULL}
(1 row)
或从l1到l2。
given = [[0,5,4,9,0],
[2,1,4,9,9]]
预期答案是:
0>>0
1>>1
2>>2
3>>3
4>>3
5>>4
9>>5
这样做有多简单?
我的审判很脏:
l1 = [0,1,2,3,4,5,9]
l2 = [0,1,2,3,3,4,5]
我更喜欢numpy方法。
答案 0 :(得分:1)
使用字典作为翻译:
>>> given = [[0,5,4,9,0],
... [2,1,4,9,9]]
>>> translation = {4:3, 5:4, 9:5}
>>> [[translation.get(x, x) for x in sub] for sub in given]
[[0, 4, 3, 5, 0], [2, 1, 3, 5, 5]]
您只需要为实际更改的数字提供映射,因为如果找不到密钥,dict.get(key, default)
将返回给定的默认值。
答案 1 :(得分:0)
对于您的确切问题(如果您拒绝使用地图,列表推导,词典或Numpy之外的任何其他简单和Pythonic方法)为什么不继续使用两个额外的行?
given[given==4]=3
given[given==5]=4
given[given==9]=5
答案 2 :(得分:0)
使用从l1
和l2
构建的替换函数:
>>> given = [[0,5,4,9,0], [2,1,4,9,9]]
>>> l1 = [0,1,2,3,4,5,9]
>>> l2 = [0,1,2,3,3,4,5]
>>> change = dict(zip(l1, l2)).get
>>> [map(change, g) for g in given]
[[0, 4, 3, 5, 0], [2, 1, 3, 5, 5]]