Answer the question
In order to leave comments, you need to log in
How to automatically make all unknown index values in an array equal to 0?
I want to shorten my code
test_list = {
'arr_1':['red','blue','yellow'],
'arr_2':['green','brown','black'],
'arr_3':['red','white','black','green']
}
test_id = {}
for x in range(3):
for key in test_list:
try:
test_id[key]
except KeyError:
test_id[key] = 0
print("text-{} border-{} shadow-{} background-{}".format(
test_list['arr_3'][min(test_id['arr_3'],len(test_list['arr_3'])-1)],
test_list['arr_2'][min(test_id['arr_2'],len(test_list['arr_2'])-1)],
test_list['arr_2'][min(test_id['arr_2']+1,len(test_list['arr_2'])-1)],
test_list['arr_1'][min(test_id['arr_1'],len(test_list['arr_1'])-1)]
))
for key in test_list:
if key == 'arr_2' or key == 'arr_3':
sum = 2
else :
sum = 1
test_id[key] = min(test_id[key]+sum,len(test_list[key])-1)
text-red border-green shadow-brown background-red
text-black, border-black shadow-black background-blue
text-green border-black shadow-black background-yellow
Answer the question
In order to leave comments, you need to log in
So not to recalculate the test_list array at the beginning of for x in range(3)
test_id = {k:0 for k in test_list}
test_id = dict.fromkeys(test_list, 0)
# словарь смещений индекса на каждом цикле
inc = {
'arr_1':1,
'arr_2':2,
'arr_3':2
}
for i in range(5):
print("text-{} border-{} shadow-{} background-{}".format(
test_list['arr_3'][min(i*inc['arr_3'], len(test_list['arr_3'])-1)],
test_list['arr_2'][min(i*inc['arr_2'], len(test_list['arr_2'])-1)],
test_list['arr_2'][min(i*inc['arr_2']+1, len(test_list['arr_2'])-1)],
test_list['arr_1'][min(i*inc['arr_1'], len(test_list['arr_1'])-1)]
))
выдаст
text-red border-green shadow-brown background-red
text-black border-black shadow-black background-blue
text-green border-black shadow-black background-yellow
text-green border-black shadow-black background-yellow
text-green border-black shadow-black background-yellow
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question