简体   繁体   English

将数字列表插入字典

[英]Insert a list of numbers into a dictionary

Following on from my previous question: here I Asked how to check if current element it's smaller than the next elements and count them.继我之前的问题之后: here I Asked how to check if current element is小于下一个元素并计算它们。

Now, I want to do something else, I want to create a dictionary that stores the values in the following way:现在,我想做其他事情,我想创建一个字典,以下列方式存储值:

input:输入:

 A = [5, 4, 3, 2]

output: output:

{'key_5': [4,3,2], 'key_4': [3,2], 'key_3': [1], 'key_2': [0]}

Explanation:解释:

  • 4,3,2 is less than 5 4,3,2小于5
  • 3,2 is less than 4 3,2 小于 4
  • 2 is less than 3 2 小于 3
  • and 2 is the last element and nothing is less than it. 2 是最后一个元素,没有什么比它少的了。
A = [5, 4, 3, 2]
res = {}
dp = [0]*len(A)
for i in range(len(A)):
    for j in range(i, len(A)):
        if A[i] > A[j]:
            dp[i] += 1 #Counts how many times each element appears in the list.
            res[f'key_{A[i]}'] = A[j] #Trying to add elements to dictionary.

print(res)

And my output is:而我的 output 是:

{'key_5': 2, 'key_4': 2, 'key_3': 2}

Using dict/list comprehensions:使用 dict/list 理解:

>>> A = [5, 4, 3, 2]
>>> {f"key_{n}": [i for i in A if i < n] or [0] for n in A}
{'key_5': [4, 3, 2], 'key_4': [3, 2], 'key_3': [2], 'key_2': [0]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM