Suppose I have the following:
cell_list = ['B1', 'B2', 'B3']
cell_data = ['1', '2', '3']
How can I build a single loop (presumably, a for
loop) with the following result in Python?
B1: 1
B2: 2
B3: 3
Suppose I have the following:
cell_list = ['B1', 'B2', 'B3']
cell_data = ['1', '2', '3']
How can I build a single loop (presumably, a for
loop) with the following result in Python?
B1: 1
B2: 2
B3: 3
The usual way in Python to iterate over 2 or more iterables simultaneously is to use the zip
function, which creates a list of tuples. Each tuple in the resulting list contains corresponding elements from each iterable.
cell_list = ['B1', 'B2', 'B3']
cell_data = ['1', '2', '3']
for t in zip(cell_list, cell_data):
print('%s: %s' % t)
output
B1: 1
B2: 2
B3: 3
If you prefer to use the more modern print
syntax, change the print line to this:
print('{0}: {1}'.format(*t))
In versions of Python newer than 2.6, you can write that like this:
print('{}: {}'.format(*t))
The easiest way would be to zip
the lists and apply the dict
to the result:
result = dict (zip (cell_list, cell_data))
Having said that, if you absolutely have to use a for
loop like the question tags suggest, you could loop over the lists and treat one as potential keys and the other as potential values:
result = {}
for i in range(len(cell_list)):
result[cell_list[i]] = cell_data[i]
for index in range(len(cell_list)) :
print cell_list[index] + ": " + cell_data[index]
Note that this code is not tested as I am posting from my phone.
What this does is it used the range object with the for loop so it will iterate over the values from 0 to the length of your list. Therefore, since your lists are parallel, you can use this index to print the item in both lists.
>>> cell_list = ['B1', 'B2', 'B3']
>>> cell_data = ['1', '2', '3']
>>> for a, b in zip(cell_list, cell_data):
print '{0}: {1}'.format(a, b)
B1: 1
B2: 2
B3: 3
Here is a solution using a for loop:
for i in range(len(cell_list)):
print (cell_list[i] + ": " + cell_data[i])