如何遍历2个列表并在Python中组合结果

时间:2018-03-29 13:59:44

标签: python python-3.x list

我正在尝试遍历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

4 个答案:

答案 0 :(得分: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而不是括号的字符串。

答案 1 :(得分:0)

你有两个相同长度的列表, 所以这只是一块蛋糕。

你可以这样做,

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])

这应该做的工作!

  

快乐编码!!

答案 2 :(得分:-1)

如果两个数组的长度相同,则可以执行以下操作:

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答案,了解更好的方法和更多解释。

答案 3 :(得分:-1)

这是一个解决方案:

private System.Windows.Forms.BindingSource bsContractors;
private System.Windows.Forms.ComboBox cmbContract_Contractors;        

bsContractors = new System.Windows.Forms.BindingSource(this.components);
bsContractors.DataSource = typeof(Contractor);
bsContractors.BindingComplete += new System.Windows.Forms.BindingCompleteEventHandler(this.bsBindingComplete);

cmbContract_Contractors.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.bsProject, "ContractorId", true));
cmbContract_Contractors.DataSource = this.bsContractors;