简体   繁体   English

在python中迭代期间创建一个“动态列表”

[英]Create a 'dynamic list' during iteration in python

Background 背景

Let there be a set of integers 让我们有一组整数

trialinteg = [231,355,112,1432,2434,5235,7896,7776,27421,42342]

Then it is possible to classify them into different equivalence classes modulo 6 然后可以将它们分类为模6的不同等价类

Problem 问题

Could we create an algorithm to classify all these integers into their respective equivalence class and store the results in a dictionary in python? 我们可以创建一个算法来将所有这些整数分类到它们各自的等价类中,并将结果存储在python中的字典中吗?

For example 例如

d = {"class0": [112,1432,..], "class1": [231,...], ...}

More importantly, can we make d changes its size and names of the keys as the integer by which we define equivalence class (in this example, 6) changes? 更重要的是,我们可以将其大小和键名更改为我们定义等价类(在此示例中为6)更改的整数吗?

Progress 进展

It is possible to store all integers of equivalence class 0 modulo 6 in a list. 可以在列表中存储等价类0模6的所有整数。 But it is not clear how one can create a 'dynamic' dictionary that adjusts its size and names of the key when the integer in question changes (for example from 6 to 121). 但是,当有问题的整数发生变化时(例如从6到121),人们如何创建一个“动态”字典来调整其大小和密钥名称尚不清楚。

moduloclasszero=[]
for num in trialinteg:
    while num % 6 != 0:

        print(f"{num} is not of class 0")
        print(f"But {num} is of class {num % 6}")
        print("now proceed to restore it to 0")

        num = num + (6-(num % 6))
    else: 
        print(f"{num} is of class 0")
        moduloclasszero.append(num)

You could use collections.defaultdict : 你可以使用collections.defaultdict

from collections import defaultdict

trialinteg = [231,355,112,1432,2434,5235,7896,7776,27421,42342]

d = defaultdict(list)

for x in trialinteg:
    d[f'class{x % 6}'].append(x)

print(d)
# defaultdict(<class 'list'>, {'class3': [231, 5235], 'class1': [355, 27421], 'class4': [112, 1432, 2434], 'class0': [7896, 7776, 42342]})

Use the class value itself for your dictionary key. 将类值本身用于字典键。

my_mod = 6
for num in trialinteg:
    d[num % my_mod].append(num)

I'll assume that you can already handle initializing the dict; 我假设你已经可以处理初始化dict; if not, look at supporting questions on this site. 如果没有,请查看本网站上的支持问题。

A dict comprehension can do this in a single assignment statement: 字典理解可以在单个赋值语句中执行此操作:

trial = [231,355,112,1432,2434,5235,7896,7776,27421,42342]
d = {equi: [i for i in trial if i%my_mod == equi] 
     for equi in range(my_mod)}

Resulting value of d: 产生的d值:

{0: [7896, 7776, 42342],
 1: [355, 27421],
 2: [],
 3: [231, 5235],
 4: [112, 1432, 2434],
 5: [] }

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

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