Python序列翻译

2024-05-26 22:57:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个元组列表,比如[(0, 34), (1, 77), (2, 6), (3, 60), (6, 2), (7, 5), (9, 13), (14, 2)]。我需要保持元组的顺序,并用0到n-1的整数重新计算第二个元素,其中n是列表长度。结果应该是[(0, 4), (1, 6), (2, 2), (3, 5), (6, 0), (7, 1), (9, 3), (14, 0)]。在

我开始编写一个接受整数序列但不接受整数对的函数:

def translation(seq):
    return [sorted(set(seq)).index(x) for x in seq]

>>> translate([34, 77, 6, 60, 2, 5, 13, 2])
[4, 6, 2, 5, 0, 1, 3, 0]

`


Tags: 函数元素列表forindexreturn顺序def
2条回答

试试这个。我修改了你给出的代码,这样你就容易理解了。在

def translation(seq):
    return [(x[0], sorted(seq, key=lambda t: t[1]).index(x)) for x in seq]

示例用法:

^{pr2}$

sorted中的key参数允许您传递一个函数来进行排序,函数lambda t: t[1]允许每个元组的第二个元素用于排序。在

更新

我更新了我的解决方案,使translation([(1, 8), (4, 9), (12, 8)])返回[(1, 0), (4, 1), (12, 0)]。在

def translation(seq):
    l = list(set(sorted([x[1] for x in seq])))
    return [(x[0], l.index(x[1])) for x in seq]

可能是这样:

xs = [(0, 34), (1, 77), (2, 6), (3, 60), (4, 2), (5, 5), (6, 13)] 
secs = sorted(set(x[1] for x in xs))
res = [(x[0], secs.index(x[1])) for x in xs]
print res # [(0, 4), (1, 6), (2, 2), (3, 5), (4, 0), (5, 1), (6, 3)]

或者是一个单一的理解(但是有二次方的表现):

^{pr2}$

相关问题 更多 >

    热门问题