簡體   English   中英

在python中迭代期間創建一個“動態列表”

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

背景

讓我們有一組整數

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

然后可以將它們分類為模6的不同等價類

問題

我們可以創建一個算法來將所有這些整數分類到它們各自的等價類中,並將結果存儲在python中的字典中嗎?

例如

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

更重要的是,我們可以將其大小和鍵名更改為我們定義等價類(在此示例中為6)更改的整數嗎?

進展

可以在列表中存儲等價類0模6的所有整數。 但是,當有問題的整數發生變化時(例如從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)

你可以使用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]})

將類值本身用於字典鍵。

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

我假設你已經可以處理初始化dict; 如果沒有,請查看本網站上的支持問題。

字典理解可以在單個賦值語句中執行此操作:

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)}

產生的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