Dictionary use instead of dynamic variable names in Python

后端 未结 3 964
不思量自难忘°
不思量自难忘° 2021-01-22 04:07

I have a long text file having truck configurations. In each line some properties of a truck is listed as a string. Each property has its own fixed width space in the string, su

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-22 04:17

    If the number of keys is more than 10,000, then this method is not viable. Otherwise define a dictionary d = {} and do a loop over your lines:

    key = line[:4]
    if not key in d.keys():
        d[key] = []
    d[key] += [somevalue]
    

    I hope this helps.

提交回复
热议问题