python - List of variable length lists -
i want have n lists of different length , refer them list. possible. example, can hard code:
list1 = [0, 2, 3, 4, 1] list2 = [1, 4, 2, 1] list4 = [1, 1, 0]
and refer them directly, able call list[1][1]
, same thing list1[1]
return or have list[3][2]
return error since list3
not defined (and list[3]
have length 0).
is possible?
i looking way dynamically create list of lists , append various lists later.
you try initializing list
lists = [[] _ in xrange(3)]
now when assigning elements, do:
lists[0].append(value) lists[2].append(value2)
which add value first sublist within lists, value2 third sublist , on..
you can use approach dict also.
>>> data = {'list%i' % : [] in range(4)} >>> data {'list0': [], 'list1': [], 'list2': [], 'list3': []}
so append items in list way
>>> data['list1'].append(1) >>> data {'list0': [], 'list1': [1], 'list2': [], 'list3': []}
Comments
Post a Comment