为什么列表结果与预期不同?

2024-04-19 05:35:51 发布

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

我有一个整数列表。然后我想改变这个列表,让它不包含,比如说一行四个1:s,而是说[[4, 1]]。所以我做了一个函数,但是得到了一个意想不到的结果。你知道吗

这就是函数

compressed3 = []

def repeat_comp(data):
    rep = 1

    for i, item in enumerate(data):
        if i < len(data) - 1:
            if item == data[i + 1]:
                rep += 1

            else:
                compressed3.append([rep, data[i - 1]])
                rep = 1

        else:
            if item == data[i - 1]:
                rep += 1

            else:
                compressed3.append([rep, data[i - 1]])
                rep = 1

repeat_comp(compressed2)

这是compressed2列表

[0,
 1,
 2,
 3,
 1,
 1,
 1,
 1,
 4]

下面是函数的结果与预期结果的比较

# output of function
[[1, 2832], # why this? (this number is one less than the lenght of another list that has nothing with this list to do)
 [1, 0],
 [1, 1],
 [1, 2],
# excluded value here
 [4, 1],
 [1, 1], # why this?
 [1, 4]]

# expected result
[[1, 0],
 [1, 1],
 [1, 2],
 [1, 3],
 [4, 1],
 [1, 4]]

Tags: of函数列表dataifthisitemelse
2条回答

这很好地说明了为什么函数应该是idempotent,也就是说,对于相同的输入,函数的每次调用都应该产生相同的结果。通过将结果列表compressed3移到函数之外,调用者要确定哪些调用会改变这个全局变量;几乎不可避免地,会出现混淆的结果。你知道吗

我将使用^{}编写如下函数:

from itertools import groupby

def compress_runs(lst):
    return [[len(list(v)), k] for k, v in groupby(lst)]

if __name__ == "__main__":
    print(compress_runs([1, 1, 1, 2, 2, 3, 3, 4, 5, 5, 6])) 
    # => [[3, 1], [2, 2], [2, 3], [1, 4], [2, 5], [1, 6]]

您只需更改代码中的两个内容即可获得预期的结果:

def repeat_comp(data):
    rep = 1
    compressed3 = []

    for i, item in enumerate(data):
        if i < len(data) - 1:
            if item == data[i + 1]:
                rep += 1

            else:
                compressed3.append([rep, item])
                rep = 1

        else:
            if item == data[i - 1]:
                rep += 1

            else:
                compressed3.append([rep, item])
                rep = 1
    return compressed3

compressed3列表移到函数中,让函数返回它,这样每次调用函数时compressed3都会被清除。然后可以将返回的列表分配给另一个变量:

result = repeat_comp(compressed2)

我把data[i - 1]改成了item

print(result)会给你[[1, 0], [1, 1], [1, 2], [1, 3], [4, 1], [1, 4]]

相关问题 更多 >