# Combining a string and integer and printing

2729 views
0

Given the Below Lists:

``````a = ['abc','cde','efg']
b = [[1,2,3],[2,3,4],[4,5,6]]
``````

What is an optimized way to print the output as shown below: Looking for an optimized way as in real I have about 100 x 100 elements. Also keep in mind that each element in b is an integer while in a is a string

``````abc,1,2,3
cde,2,3,4
efg,4,5,6
``````

0

To print in the exact format you specified:

``````print('\n'.join([a[i] + ',' + str(b[i]).strip('[').strip(']').replace(' ','') for i in range(len(a))]))
``````

Output:

``````abc,1,2,3
cde,2,3,4
efg,4,5,6
``````

100*100 element is a very small number for a python program - any optimization at this scale will probably fail to be significant enough for us humans to have noticed. To test:

``````%%timeit
array = np.random.randn(100,100)
print('\n'.join([str(e) for e in array])) # prints like above
``````

result:

``````148 ms ± 13.2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
``````

Also - keep in mind the main bottle neck should be the `print`, not the actual process doing the printing, hence using `zip` or other trick may not work as they don't help the terminal/other stdout capture print fast enough.

posted this
3

Use `range`,

``````for i in range(len(b)):
print("{},{}".format(a[i],','.join([str(x) for x in b[i]])))

#output,
abc,1,2,3
cde,2,3,4
efg,4,5,6
``````

posted this