如何比较两个列表中每个值的索引 python

How to compare index of each value in two lists python

我有一个包含 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:

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'}

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

我不知道你是如何生成这 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 方式。