【问题标题】:How to loop through 2 lists and combine the results in Python [duplicate]如何遍历2个列表并在Python中组合结果[重复]
【发布时间】:2018-09-08 12:42:04
【问题描述】:

我正在尝试遍历 2 个列表并组合结果并将其写入文件,但是我可以找到一种方法来执行此操作。

hosts = ['host1', 'host2', 'host3']
ips = ['ip1', 'ip2', 'ip3']
filename = 'devicelist.txt'

with open(filename, 'w') as out_file:
    for i in ips:
        for h in hosts:
            out_file.write(h + ' - ' + i + '\n')

这基本上贯穿了所有可能的组合,但这不是我要寻找的结果。 我在看的是这样的:

host1 - ip1
host2 - ip2
host3 - ip3

【问题讨论】:

标签: python python-3.x list


【解决方案1】:

此代码中的问题是您首先循环遍历一个列表,然后遍历另一个列表。您可以通过使用zip 函数将两者结合起来轻松解决此问题。这结合了两个这样的列表:

a = [1,2,3]
b = [4,5,6]
c = zip(a,b)

这里

c = [(1, 4), (2, 5), (3, 6)]

现在这样做:

hosts = ['host1', 'host2', 'host3']
ips = ['ip1', 'ip2', 'ip3']

#if the lists don't have the same length, you'll get an incomplete list here!
output = zip(hosts, ips)

获取您可以使用以下方式写入文件的组合列表:

with open('devicelist.txt', 'w') as out_file:
    for i in output:
          out_file.write('{} - {} \n'.format(i[0], i[1]))

'{}'.format(x) 输出带有 x 而不是括号的字符串。

【讨论】:

    【解决方案2】:

    你有两个相同长度的列表, 所以这只是小菜一碟。

    你可以这样做,

    filename = 'devicelist.txt' 
    open(filename, 'w') # Creates File.
    hosts = ['host1', 'host2', 'host3']
    ips = ['ip1', 'ip2', 'ip3']
    with open(filename, 'a') as f:
           for i in range(len(hosts)):
                f.write(hosts[i]+' - '+ips[i])
    

    这应该做的工作!

    编码愉快!!

    【讨论】:

      【解决方案3】:

      如果两个数组的长度相同,你可以这样做:

      for i in xrange(length):  # length is any of the arrays length
          out_file.write(hosts[i] + ' - ' + ips[i] + '\n')
      

      这可以简化为:

      newList = [hosts[i] + ' - ' + ips[i] + '\n' for i in xrange(length)]
      
      with open(filename, 'w') as out_file:
          for element in newList:
                  out_file.write(element)
      

      查看this 答案以获得更好的方法和更多解释。

      【讨论】:

      • 我重读了他的问题和他的清单。列表理解将是理想的
      【解决方案4】:

      这里有一个解决方案:

      hosts = ['host1', 'host2', 'host3']
      ips = ['ip1', 'ip2', 'ip3']
      
      assert len(hosts) == len(ips) # check that the 2 list are the same lenght
      
      with open('devicelist.txt', 'w') as out_file:
          for i in xrange(len(ips)):
              out_file.write(hosts[i] + ' - ' + ips[i] + '\n')
      

      【讨论】:

        猜你喜欢
        • 2011-04-26
        • 1970-01-01
        • 2023-03-23
        • 2020-02-21
        • 2012-08-22
        • 1970-01-01
        • 1970-01-01
        • 2017-04-12
        • 1970-01-01
        相关资源
        最近更新 更多