[python] generate lists based on the information in the dictionary, each time getting longer.

demand

Key and value are saved in

key_counts. Generate a list and generate value key based on the number of value.

question

finds that each time you loop, there is an extra null value at the end of the generated new list.

Code

key_counts = [{"key": "qj", "value": 3}, {"key": "wuhan", "value": 2}, {"key": "xy", "value": 2}, {"key": "zz", "value": 10}]
total = 17 -sharp 

v1 = ["" for x in range(total)]
print(v1)

count = 0
for key_count in key_counts:
    start = count
    end = start + key_count["value"] - 1
    count = end + 1
    print(start, end, key_count["key"])
    xlist = [key_count["key"] for x in range(key_count["value"])]
    print(xlist)
    v1[start:end] = xlist
    print(v1)

output results

[",","]
0 2 qj
["qj"," qj", "qj"]
[" qj","", "",""]
34 wuhan
["wuhan"," wuhan"]
["qj"," wuhan", "wuhan","",
56 xy
["xy"," xy"]
["qj"," wuhan", "wuhan"," xy", "xy","]
7 16 zz
["zz"," zz", "zz"," zz"]
["qj"," wuhan", "wuhan"," xy", "xy"," zz",", ""]

At the end of the

list, with each loop, an additional element is added (which may be misunderstood. )

Apr.11,2021

list slicing error.
should be changed to:

v1[start:(end+1)] = xlist

end = start + key_count ['value']-1
xlist = [key_count [' key'] for x in range (key_count ['value']]
the main problem lies in these two lines of code
the length of each slice is 1
less than the length of xlist, and the slice assignment of Python does not require the same length, for example:
L = [1]
L [: 1] = [5J 5L5]

because each slice assignment in the loop increases the length of v1 by 1, so you are confused

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e62438-4dd30.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e62438-4dd30.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?