Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

python - Parallelly looping over different lengths

The idea is while iterating over a dictionary variable's each key, to take the first integer from each key, then in the next iteration, each key's second integer should be taken from the list, then only the third integer from each key, and so on.

I have the desired output, however, I would like to make it as universal as possible. Meaning that, instead of a static index order application, I would like two parallel loops. (probably izip is the solution)

My code:

dictionary = {0:[9, 9, 10, 8, 8, 8, 8], 1: [12,9,8,9,9,6,7], 2:[12, 12, 12, 10, 8, 9, 6], 3:[11, 10, 9, 12, 11, 10, 9]}

horizontal_dict = {}      
l1 = [] 
l2 = [] 
l3 =[] 
l4 = [] 
l5 =[] 
l6= []
l7 = []
for i in range(len(dictionary)):
    l1.append(dictionary[i][0])
    l2.append(dictionary[i][1])
    l3.append(dictionary[i][2])
    l4.append(dictionary[i][3])
    l5.append(dictionary[i][4])
    l6.append(dictionary[i][5])
    l7.append(dictionary[i][6])
    
    horizontal_dict[1] = l1
    horizontal_dict[2] = l2
    horizontal_dict[3] = l3
    horizontal_dict[4] = l4
    horizontal_dict[5] = l5
    horizontal_dict[6] = l6
    horizontal_dict[7] = l7        

Result of dictionary:

dictionary
Out[38]: 
{0: [9, 9, 10, 8, 8, 8, 8],
 1: [12, 9, 8, 9, 9, 6, 7],
 2: [12, 12, 12, 10, 8, 9, 6],
 3: [11, 10, 9, 12, 11, 10, 9]}

Desired result:

horizontal_dict
Out[37]: 
{1: [9, 12, 12, 11],
 2: [9, 9, 12, 10],
 3: [10, 8, 12, 9],
 4: [8, 9, 10, 12],
 5: [8, 9, 8, 11],
 6: [8, 6, 9, 10],
 7: [8, 7, 6, 9]}

question from:https://stackoverflow.com/questions/66050994/parallelly-looping-over-different-lengths

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use loops:

dictionary = {
    0: [9, 9, 10, 8, 8, 8, 8],
    1: [12, 9, 8, 9, 9, 6, 7],
    2: [12, 12, 12, 10, 8, 9, 6],
    3: [11, 10, 9, 12, 11, 10, 9, 13]
}

new = {}

for n in range(max(len(v) for v in dictionary.values())):
    new[n] = []
    for k, lst in dictionary.items():
        if n < len(lst):
            new[n].append(lst[n])
        else:
            # no element at index n
            # use a default value!
            new[n].append(-1)

print(new)

Out:

{0: [9, 12, 12, 11],
 1: [9, 9, 12, 10],
 2: [10, 8, 12, 9],
 3: [8, 9, 10, 12],
 4: [8, 9, 8, 11],
 5: [8, 6, 9, 10],
 6: [8, 7, 6, 9],
 7: [-1, -1, -1, 13]}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...