loops - Python Iterate an integer as long as elements exist in a list -
i have list looks this:
data = [['info', 'numbers', 'more info'], ['info', 'numbers', 'more info'], ['..*this dynamic have hundreds*..']] data read in dynamic file , split this, number of elements unknown.
what trying rejoin information ':' between items , store text file per line problem loop iterate through data elements , increment integer used on data list.
here snippet:
#not sure type of loop use here # iterate through data list. savethis = ':'.join(data[n]) file2.write(savethis+'\n') thanks
flatten list, then join. itertools.chain.from_iterable() flattening:
from itertools import chain ':'.join(chain.from_iterable(data)) this put : between all items in sublists, writing them out 1 long string.
demo:
>>> itertools import chain >>> ':'.join(chain.from_iterable(data)) 'info:numbers:more info:info:numbers:more info:..*this dynamic have hundreds*..' if need sublist each written new line, loop on data:
for sublist in data: file2.write(':'.join(sublist) + '\n') or use nested list comprehension:
file2.write('\n'.join(':'.join(sublist) sublist in data) + '\n')
Comments
Post a Comment