Python 3中相同输入的列表和字典输出不匹配

时间:2021-04-21 03:12:47

I have the following function which makes use of a dictionary of cycle_times to generate lists and dictionaries containing elements whose values are greater than a certain threshold.

我有以下函数,它使用cycle_times的字典来生成包含值大于某个阈值的元素的列表和字典。

def anamolous_cycle_time_index_and_lengths(cycle_time_dict, anamoly_threshold):
    for meter,cycle_time_list in cycle_time_dict.items():
        anamoly_dict = {cycle_time_list.index(x):x for x in cycle_time_list if x > anamoly_threshold}
        anamoly_list = [x for x in cycle_time_list if x > anamoly_threshold]
        print(meter,len(anamoly_dict))
        print([value for key,value in anamoly_dict.items()])
        print(anamoly_list) 

Suppose I give the inputs as

假设我将输入作为

new_dict = {104:[2,3,4,5,6,7,3,2,5,6,7], 101:[2,45,4,2,5,2,34,2,5,6,7], 106:[2,23,4,5,65,7,3,23,5,6,7]}
anamoly_threshold = 3

The outputs I get are

我得到的输出是

104 4
[4, 5, 6, 7]
[4, 5, 6, 7, 5, 6, 7]
101 6
[45, 4, 5, 34, 6, 7]
[45, 4, 5, 34, 5, 6, 7]
106 6
[23, 4, 5, 65, 7, 6]
[23, 4, 5, 65, 7, 23, 5, 6, 7]

Shouldn't the list and dictionary give me the same output? I have run a comprehension for both data structures on the same data.

列表和字典不应该给我相同的输出吗?我已经对同一数据上的两个数据结构进行了理解。

1 个解决方案

#1


0  

Your problem is the use of .index(x). This returns the index for the first occurrence of x. And since dictionary keys are unique, you will see only the first occurrence of duplicate elements in your dict comprehension.
There are several ways to overcome this problem. The easiest is to use enumerate:

你的问题是使用.index(x)。这将返回第一次出现的x的索引。由于字典键是唯一的,因此您只会在dict理解中看到第一次出现重复元素。有几种方法可以解决这个问题。最简单的是使用枚举:

anamoly_dict = {index: x for index, x in enumerate(cycle_time_list) if x > anamoly_threshold}

Now the output for both methods is the same.

现在两种方法的输出都是一样的。

#1


0  

Your problem is the use of .index(x). This returns the index for the first occurrence of x. And since dictionary keys are unique, you will see only the first occurrence of duplicate elements in your dict comprehension.
There are several ways to overcome this problem. The easiest is to use enumerate:

你的问题是使用.index(x)。这将返回第一次出现的x的索引。由于字典键是唯一的,因此您只会在dict理解中看到第一次出现重复元素。有几种方法可以解决这个问题。最简单的是使用枚举:

anamoly_dict = {index: x for index, x in enumerate(cycle_time_list) if x > anamoly_threshold}

Now the output for both methods is the same.

现在两种方法的输出都是一样的。