Reputation: 143
I have a list of 6 files and a list of 6 mac addresses. Each mac address corresponds to the file in the same list slot. For instance, mac_list[1]
corresponds to file_list[1]
, mac_list[2]
corresponds to file_list[2]
, etc. Each file already contains a mac address which is incorrect, so I need to overwrite the incorrect one with the new one (from mac_list
) which exists at the corresponding index in mac_list
. The actual replacement of each mac address I know how to do with sed. What I don't know how to do is only access the values which exist at the same index in both lists. My initial thought was to use a nested for loop for both lists and compare their indexes:
for addr in mac_list:
for file in file_list:
if addr.index == file.index:
#overwrite mac address
But is there a more efficient approach to this?
Upvotes: 0
Views: 360
Reputation: 9572
In general you usually don't need to use index
of arrays in Python, unless you really are implementing complex algorithms.
but for completeness this is how you would solve it using indexes:
for idx, addr in enumerate(mac_list):
file = file_list[idx]
#...
as the other answers mention, zip
is the pythonic way to do it.
Upvotes: 0
Reputation: 81604
I don't know how you generate the 2 lists, but it will be much more efficient to generate a dict, then you can do O(1) lookup with no need to iterate.
If you insist on 2 lists, then:
for index, file in enumerate(file_list):
relevant_mac = mac_list[index]
Or zip
as been suggested in other answers.
Upvotes: 0
Reputation: 8520
zip
is the easiest approach:
mac_list = [1, 2, 3] # for example
file_list = [4, 5, 6]
for item1, item2 in zip(mac_list, file_list):
print(item1, item2)
#overwrite mac address
# prints:
# 1 4
# 2 5
# 3 6
Upvotes: 1
Reputation: 12920
>>> file_list=[1,2,3]
>>> mac_list=['x','y','z']
>>> zip(file_list,mac_list)
<zip object at 0x10a2c1388>
>>> list(zip(file_list,mac_list))
[(1, 'x'), (2, 'y'), (3, 'z')]
>>> dict(zip(file_list,mac_list))
{1: 'x', 2: 'y', 3: 'z'}
Upvotes: 0
Reputation: 22776
You need to use zip
:
for addr, file in zip(mac_list, file_list):
# to-do
You can alternatively but not-preferably use a common index counter:
# if the lists have the same length
for i in range(len(mac_list)):
addr, file = mac_list[i], file_list[i]
# to-do
# if you're not sure that they have the same length
l = min(len(mac_list), len(file_list))
for i in range(l): # if the lists have the same length
addr, file = mac_list[i], file_list[i]
# to-do
Upvotes: 0