我有一个包含6个文件的列表和一个包含6个mac地址的列表。每个mac地址对应于同一列表槽中的文件。例如,mac_list[1]
对应file_list[1]
,mac_list[2]
对应file_list[2]
等。每个文件已经包含一个不正确的mac地址,所以我需要用mac_list
中相应索引处存在的新地址(来自mac_list
)覆盖不正确的地址。 。实际更换每个mac地址我知道如何处理sed。我不知道该怎么做只访问两个列表中同一索引处存在的值。我最初的想法是为两个列表使用嵌套for循环并比较它们的索引:
for addr in mac_list:
for file in file_list:
if addr.index == file.index:
#overwrite mac address
但是有更有效的方法吗?
zip
是最简单的方法:
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
你需要使用zip
:
for addr, file in zip(mac_list, file_list):
# to-do
您可以选择但不是 - 最好使用公共索引计数器:
# 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
>>> 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'}
我不知道你是如何生成2个列表的,但是生成dict会更有效率,然后你可以进行O(1)查找而不需要迭代。
如果您坚持2个列表,那么:
for index, file in enumerate(file_list):
relevant_mac = mac_list[index]
或者在其他答案中提出了zip
。
通常,您通常不需要在Python中使用index
数组,除非您真的在实现复杂的算法。但为了完整性,这是你如何使用索引解决它:
for idx, addr in enumerate(mac_list):
file = file_list[idx]
#...
正如其他答案所提到的那样,zip
是这样做的pythonic方式。